乐闻世界logo
搜索文章和话题

How can I measure the execution time of a npm/yarn task/script?

1个答案

1

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:

  1. Using the time command
  • On Unix-like systems (such as Linux and macOS), you can use the built-in time command to measure command execution time. For example, if you have an npm script named build, run it in the command line:
bash
time npm run build
  • This outputs the execution time of the build script, including user time, system time, and wall-clock time.
  1. Modifying scripts in package.json
  • Add time measurement functionality to the scripts section in package.json. For instance, modify a script to:
json
"scripts": { "build": "time webpack --config webpack.config.js" }
  • This ensures that every npm run build execution measures and displays the webpack execution time.

For yarn:

  1. Using the time command
  • Similar to npm, use the time command to measure any yarn script's execution time. The command format is:
bash
time yarn run build
  • This outputs the execution time, including various time metrics.
  1. Using the --verbose flag
  • Yarn provides a --verbose flag that outputs detailed information, including time statistics, during script execution. Run the command as follows:
bash
yarn 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 time command to key scripts in package.json and 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 回复

你的答案