how to use process.hrtime to get execution time of async function

Since Node 10.7.0, process.hrtime is marked as 'legacy', with the recommended method being process.hrtime.bigint. The documentation contains an example of how to use this method to time an operation:

const start = process.hrtime.bigint();
// 191051479007711n

setTimeout(() => {
  const end = process.hrtime.bigint();
  // 191052633396993n

  console.log(`Benchmark took ${end - start} nanoseconds`);
  // Benchmark took 1154389282 nanoseconds
}, 1000);

Got it:

console.log("starting");
var start = process.hrtime();
console.log("start");
console.log(start);

setTimeout(function(){
    console.log("HELLO");
    var end = process.hrtime(start);
    console.log("end");
    console.log(end);
}, 1000);

Prints

starting
start
[ 132798, 207101051 ]
HELLO
end
[ 1, 7001730 ]

That means 1 second and 7001730 nanoseconds from start to end


Just to add in case someone needs the execution time in ms:

console.log("starting");
var start = process.hrtime();
console.log("start");
console.log(start);

setTimeout(function(){
    console.log("HELLO");
    var end = process.hrtime(start); // end[0] is in seconds, end[1] is in nanoseconds
    const timeInMs = (end[0]* 1000000000 + end[1]) / 1000000; // convert first to ns then to ms
    console.log("timeInMs:", timeInMs);
}, 1000);

Tags:

Node.Js