How to get a microtime in Node.js?
new Date().getTime()
? This gives you a timestamp in milliseconds, which is the most accurate that JS will give you.
Update: As stated by vaughan, process.hrtime()
is available within Node.js - its resolution are nanoseconds and therefore its much higher. This function returns an array [seconds, nanoseconds]
containing the current real-time high-resolution value, but note that it is not tied to any specific clock, meaning the difference in two successive values tells you how much time passed, but individual values tell you nothing meaningful.
Also note that as of Node v10, process.hrtime()
has been marked "legacy" and you should be using process.hrtime.bigint()
instead, which yields a single BigInt number rather than an array.
In Node.js, "high resolution time" is made available via process.hrtime
. It returns a array with first element the time in seconds, and second element the remaining nanoseconds.
To get current time in microseconds, do the following:
var hrTime = process.hrtime()
console.log(hrTime[0] * 1000000 + hrTime[1] / 1000)
(Thanks to itaifrenkel for pointing out an error in the conversion above.)
In modern browsers, time with microsecond precision is available as performance.now
. See https://developer.mozilla.org/en-US/docs/Web/API/Performance/now for documentation.
I've made an implementation of this function for Node.js, based on process.hrtime
, which is relatively difficult to use if your solely want to compute time differential between two points in a program. See http://npmjs.org/package/performance-now . Per the spec, this function reports time in milliseconds, but it's a float with sub-millisecond precision.
In Version 2.0 of this module, the reported milliseconds are relative to when the node process was started (Date.now() - (process.uptime() * 1000)
). You need to add that to the result if you want a timestamp similar to Date.now()
. Also note that you should bever recompute Date.now() - (process.uptime() * 1000)
. Both Date.now
and process.uptime
are highly unreliable for precise measurements.
To get current time in microseconds, you can use something like this.
var loadTimeInMS = Date.now()
var performanceNow = require("performance-now")
console.log((loadTimeInMS + performanceNow()) * 1000)
See also: Does JavaScript provide a high resolution timer?