How to get a microtime in Node.js?

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

    I'm not so proud about this solution but you can have timestamp in microsecond or nanosecond in this way:

    const microsecond = () => Number(Date.now() + String(process.hrtime()[1]).slice(3,6))
    const nanosecond = () => Number(Date.now() + String(process.hrtime()[1]).slice(3))
    
    // usage
    microsecond() // return 1586878008997591
    nanosecond()  // return 1586878009000645600
    
    // Benchmark with 100 000 iterations
    // Date.now: 7.758ms
    // microsecond: 33.382ms
    // nanosecond: 31.252ms
    

    Know that:

    • This solution works exclusively with node.js,
    • This is about 3 to 10 times slower than Date.now()
    • Weirdly, it seems very accurate, hrTime seems to follow exactly js timestamp ticks.
    • You can replace Date.now() by Number(new Date()) to get timestamp in milliseconds

    Edit:

    Here a solution to have microsecond with comma, however, the number version will be rounded natively by javascript. So if you want the same format every time, you should use the String version of it.

    const microsecondWithCommaString = () => (Date.now() + '.' + String(process.hrtime()[1]).slice(3,7))
    const microsecondWithComma = () => Number(Date.now() + '.' + String(process.hrtime()[1]).slice(3,7))
    
    microsecondWithCommaString() // return "1586883629984.8997"
    microsecondWithComma() // return 1586883629985.966
    

提交回复
热议问题