When using npm or yarn for task management, measuring the execution time of tasks or scripts is a valuable metric that helps optimize script performance. Below, I will guide you through step-by-step methods to measure the execution time of npm or yarn scripts.
For npm:
- Using the
timecommand
- On Unix-like systems (such as Linux and macOS), you can use the built-in
timecommand to measure command execution time. For example, if you have an npm script namedbuild, run it in the command line:
bashtime npm run build
- This outputs the execution time of the
buildscript, including user time, system time, and wall-clock time.
- Modifying scripts in package.json
- Add time measurement functionality to the
scriptssection inpackage.json. For instance, modify a script to:
json"scripts": { "build": "time webpack --config webpack.config.js" }
- This ensures that every
npm run buildexecution measures and displays thewebpackexecution time.
For yarn:
- Using the
timecommand
- Similar to npm, use the
timecommand to measure any yarn script's execution time. The command format is:
bashtime yarn run build
- This outputs the execution time, including various time metrics.
- Using the
--verboseflag
- Yarn provides a
--verboseflag that outputs detailed information, including time statistics, during script execution. Run the command as follows:
bashyarn run build --verbose
- This displays detailed execution logs and provides the execution time at the end.
Real-World Application Example:
- In my previous project, we needed to optimize CI/CD pipeline build times. I added the
timecommand to key scripts inpackage.jsonand analyzed task durations using CI tool logs. We discovered that certain dependency installations were slow, so we switched to a faster npm mirror source, significantly improving overall build efficiency. - By implementing this approach, we can measure each script's execution time and make data-driven optimization decisions, ultimately enhancing development and deployment efficiency.
2024年7月19日 13:19 回复