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

时间:2013-08-03 10:27:49

标签: 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);

输出

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

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

5 个答案:

答案 0 :(得分:29)

知道了:

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纳秒

答案 1 :(得分:1)

仅在有人需要以毫秒为单位的执行时间时添加:

.clear

答案 2 :(得分: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

答案 3 :(得分: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))

答案 4 :(得分:0)

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