How can I measure the execution time of a npm/yarn task on the command line without modifying the scripts.
In my special use case I want to execute an existing E2E-Test (yarn test:e2e) 100 times and take the average value.
You could use the npm package gnomon:
A command line utility, a bit like moreutils's ts, to prepend timestamp information to the standard output of another command.
Install it like this:
$ npm i -g gnomon
With this you could run:
$ yarn install | gnomon
And it might give you an output like this:
$ yarn install | gnomon
0.5327s yarn install v1.9.4
1.9652s [1/4] Resolving packages...
0.0160s success Already up-to-date.
0.0163s Done in 2.38s.
0.0003s
Total 2.5315s
Use the following command in unix
time npm run build
For windows use this command
Measure-Command { start-process npm 'run build' -wait}
If you don't want any global or even local dependencies for this, or you don't want something that only works on unixy operating systems, this is almost trivially achieved with a simple .js file and an equally simple npm script refinement:
{
...
"scripts: {
"time": "node mark.js",
"start": "npm run time && ...whatever 'start' was before... && npm run time",
},
...
}
With that mark.js
file being the almost trivial following code:
const fs = require("fs"); // or import fs from "fs"; if you're working on modern JS
const timingFile = `.timing`;
if(fs.existsSync(timingFile)) {
const end = Date.now();
const start = fs.readFileSync(timingFile);
fs.unlinkSync(timingFile);
console.log(`Runtime: ${(end - start)/1000}s`);
} else { fs.writeFileSync(timingFile, `${Date.now()}`, `utf8`); }
Inspired by @user1816491 answer, I remembered that I used to use a shell utility, ts
.
In unix (apt
is for debian/ubuntu), install moreutils
that contains ts
, as e.g.
sudo apt install moreutils -y
Then e.g.
$ npm run build | ts '%FT%T'
2022-08-24T09:55:13
2022-08-24T09:55:13 > build
2022-08-24T09:55:13 > next build
2022-08-24T09:55:13
or
$ npm run build | ts -s '[%H:%M:%.S]'
[00:00:00.416378]
[00:00:00.416511] > build
[00:00:00.416577] > next build
[00:00:00.416603]