How to get a microtime in Node.js?

Javascriptnode.jsV8

Javascript Problem Overview


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)

Javascript Solutions


Solution 1 - Javascript

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: https://stackoverflow.com/questions/6875625/does-javascript-provide-a-high-resolution-timer?lq=1

Solution 2 - Javascript

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.

Solution 3 - Javascript

now('milli'); //  120335360.999686
now('micro') ; // 120335360966.583
now('nano') ; //  120335360904333

Known that now is :

const now = (unit) => {
  
  const hrTime = process.hrtime();
  
  switch (unit) {
    
    case 'milli':
      return hrTime[0] * 1000 + hrTime[1] / 1000000;
      
    case 'micro':
      return hrTime[0] * 1000000 + hrTime[1] / 1000;
      
    case 'nano':
    default:
      return hrTime[0] * 1000000000 + hrTime[1];
  }
  
};

Solution 4 - Javascript

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()

Solution 5 - Javascript

There's also https://github.com/wadey/node-microtime:

> var microtime = require('microtime')
> microtime.now()
1297448895297028

Solution 6 - Javascript

Node.js nanotimer

I wrote a wrapper library/object for node.js on top of the process.hrtime function call. It has useful functions, like timing synchronous and asynchronous tasks, specified in seconds, milliseconds, micro, or even nano, and follows the syntax of the built in javascript timer so as to be familiar.

Timer objects are also discrete, so you can have as many as you'd like, each with their own setTimeout or setInterval process running.

It's called nanotimer. Check it out!

Solution 7 - Javascript

You can also use performance API that works both in NodeJS and Browser:

var start = performance.timing ?
    performance.timing.navigationStart :
    performance.timeOrigin;

var time = (performance.now() + start) * 1000;

The Performance API stores value in floating-point number and the fraction is microseconds.

Solution 8 - Javascript

To work with more precision than Date.now(), but with milliseconds in float precision:

function getTimeMSFloat() {
    var hrtime = process.hrtime();
    return ( hrtime[0] * 1000000 + hrtime[1] / 1000 ) / 1000;
}

Solution 9 - Javascript

Get hrtime as single number in one line:

const begin = process.hrtime();
// ... Do the thing you want to measure
const nanoSeconds = process.hrtime(begin).reduce((sec, nano) => sec * 1e9 + nano)

Array.reduce, when given a single argument, will use the array's first element as the initial accumulator value. One could use 0 as the initial value and this would work as well, but why do the extra * 0.

Solution 10 - Javascript

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

Solution 11 - Javascript

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

Solution 12 - Javascript

there are npm packages that bind to the system gettimeofday() function, which returns a microsecond precision timestamp on Linux. Search for npm gettimeofday. Calling C is faster than process.hrtime()

Solution 13 - Javascript

process.hrtime() not give current ts.

This should work.

 const loadNs       = process.hrtime(),
        loadMs       = new Date().getTime(),
        diffNs       = process.hrtime(loadNs),
        microSeconds = (loadMs * 1e6) + (diffNs[0] * 1e9) + diffNs[1]

  console.log(microSeconds / 1e3)

Solution 14 - Javascript

better?

Number(process.hrtime().join(''))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNiLLView Question on Stackoverflow
Solution 1 - JavascriptMyrne StolView Answer on Stackoverflow
Solution 2 - JavascriptNiet the Dark AbsolView Answer on Stackoverflow
Solution 3 - JavascriptAbdennour TOUMIView Answer on Stackoverflow
Solution 4 - Javascriptd4nyllView Answer on Stackoverflow
Solution 5 - JavascriptmikemaccanaView Answer on Stackoverflow
Solution 6 - Javascriptkrb686View Answer on Stackoverflow
Solution 7 - JavascriptjcubicView Answer on Stackoverflow
Solution 8 - JavascriptRossView Answer on Stackoverflow
Solution 9 - JavascriptCameron TacklindView Answer on Stackoverflow
Solution 10 - JavascriptpirsView Answer on Stackoverflow
Solution 11 - JavascriptManohar Reddy PoreddyView Answer on Stackoverflow
Solution 12 - JavascriptAndrasView Answer on Stackoverflow
Solution 13 - JavascriptSaravana Kumar ChinnarajView Answer on Stackoverflow
Solution 14 - Javascriptinfinito84View Answer on Stackoverflow