25

我正在尝试获取异步函数的执行时间。似乎我可以为此使用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);

它输出

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

但我不明白以毫秒为单位的执行时间在哪里?我希望在这个例子中得到 1000 毫秒。

4

5 回答 5

39

知道了:

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);

印刷

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

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

于 2013-08-03T10:38:48.000 回答
8

只是添加以防有人需要以毫秒为单位的执行时间:

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);
于 2019-11-05T13:00:34.167 回答
4

从 Node 10.7.0 开始,process.hrtime被标记为“legacy”,推荐的方法是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);
于 2021-05-28T08:00:05.963 回答
0

这是异步函数的简单包装计时函数:

// async function execution time wrapper
async function fnTime(fn, ...params) {
  const start = process.hrtime()
  const result = await fn(...params)
  const end = process.hrtime(start)
  console.log(
    `[${fn.name}] Execution time:${(end[0] * 1000000000 + end[1]) /
      1000000} ms`
  )
  return result
}

示例用法(请参阅repl.it上的此演示):

// usage
const setTimeoutPromise = ms => new Promise(resolve => setTimeout(resolve, ms))

// example 2:
// get name from db
const db = {
  async getUser(id){
    // simulate wait for record retrival from db
    await fnTime(setTimeoutPromise, 150)

    return {
      _id: id,
      name: 'John Doe',
      organisation: 'UN',
      email: 'johndoe@un.org'
    }
  }
}


// test it
;(async function(){
  const result = await fnTime(db.getUser, 'asfa98th4nfwef0qwrwef0')
  console.log('result', result)
})()

// result:
// [setTimeoutPromise] Execution time:197.928094 ms
// [getUser] Execution time:199.480553 ms
于 2020-04-08T03:59:57.940 回答
0

我正在使用这个。看起来更清晰一些。

const getProcessingTimeInMS = (time: [number, number]): string => {
  return `${(time[0] * 1000 + time[1] / 1e6).toFixed(2)}ms`
}

和初始化:

// Somewhere at the start
const _hrtime = process.hrtime()
...
// Somewhere at the end
getProcessingTimeInMS(process.hrtime(_hrtime))
于 2021-05-02T09:12:47.110 回答