How to get a microtime in Node.js?

后端 未结 13 1181
情深已故
情深已故 2020-12-04 13:41

How can I get the most accurate time stamp in Node.js?

ps My version of Node.js is 0.8.X and the node-microtime extension doesn\'t work for me (crash on install)

13条回答
  •  粉色の甜心
    2020-12-04 14:21

    The BigInt data type is supported since Node.js 10.7.0. (see also the blog post announcement). For these supported versions of Node.js, the process.hrtime([time]) method is now regarded as 'legacy', replaced by the process.hrtime.bigint() method.

    The bigint version of the process.hrtime() method returning the current high-resolution real time in a 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);
    

    tl;dr

    • Node.js 10.7.0+ - Use process.hrtime.bigint()
    • Otherwise - Use process.hrtime()

提交回复
热议问题