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

时间:2021-08-27 16:30:56

I am triing to get execution time of async function. Seemingly I can use process.hrtime for this. I created simple example:

我正在试图获得异步功能的执行时间。貌似我可以使用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);

It outputs

它输出

starting
start
[ 131806, 731009597 ]
HELLO
end
[ 131807, 738212296 ]

But I don't understand where is exectuion time in miliseconds? I expect to get 1000 ms in this example.

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

1 个解决方案

#1


27  

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

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

#1


27  

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

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