如何使用process.hrtime来获取异步函数的执行时间

Max*_*mov 17 node.js

我正在试图获得异步函数的执行时间.貌似我可以使用process.hrtime.我创建了简单的例子:

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

setTimeout(function(){
    console.log("HELLO");
    var end = process.hrtime();
    console.log("end");
    console.log(end);
}, 1000);
Run Code Online (Sandbox Code Playgroud)

它输出

starting
start
[ 131806, 731009597 ]
HELLO
end
[ 131807, 738212296 ]
Run Code Online (Sandbox Code Playgroud)

但我不明白在几分之一的时间里,执行时间在哪里?我期望在这个例子中得到1000毫秒.

Max*_*mov 31

得到它了:

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);
Run Code Online (Sandbox Code Playgroud)

打印

starting
start
[ 132798, 207101051 ]
HELLO
end
[ 1, 7001730 ]
Run Code Online (Sandbox Code Playgroud)

这意味着从开始到结束1秒和7001730纳秒


Lee*_*Gee 12

从 Node 10.7.0 开始,process.hrtime被标记为“旧版”,推荐的方法是process.hrtime.bigint. 该文档包含如何使用此方法来计时操作的示例:

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);
Run Code Online (Sandbox Code Playgroud)


Par*_*rth 7

只是为了以防万一有人需要以毫秒为单位的执行时间:

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);
Run Code Online (Sandbox Code Playgroud)