How to get a microtime in Node.js?

后端 未结 13 1197
情深已故
情深已故 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:29

    A rewrite to help quick understanding:

    const hrtime = process.hrtime();     // [0] is seconds, [1] is nanoseconds
    
    let nanoSeconds = (hrtime[0] * 1e9) + hrtime[1];    // 1 second is 1e9 nano seconds
    console.log('nanoSeconds:  ' + nanoSeconds);
    //nanoSeconds:  97760957504895
    
    let microSeconds = parseInt(((hrtime[0] * 1e6) + (hrtime[1]) * 1e-3));
    console.log('microSeconds: ' + microSeconds);
    //microSeconds: 97760957504
    
    let milliSeconds = parseInt(((hrtime[0] * 1e3) + (hrtime[1]) * 1e-6));
    console.log('milliSeconds: ' + milliSeconds);
    //milliSeconds: 97760957
    

    Source: https://nodejs.org/api/process.html#process_process_hrtime_time

提交回复
热议问题