Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a microtime in Node.js?

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)

like image 697
NiLL Avatar asked Jul 30 '12 16:07

NiLL


People also ask

What is Microtime function in PHP?

PHP microtime() function returns the current Unix timestamp. By default this returns a string value in the form msec sec. If you pass the boolean value true as a parameter to this method, it returns the current time in seconds since the Unix epoch accurate to the nearest microsecond.

How do I get node js terminal?

js/JavaScript code. To launch the REPL (Node shell), open command prompt (in Windows) or terminal (in Mac or UNIX/Linux) and type node as shown below. It will change the prompt to > in Windows and MAC. You can now test pretty much any Node.

How do I initialize node?

The very first thing we want to do in any new Node. js project is to initialize the project with NPM. To do that, open a command prompt at the directory you just created for your project and run npm init . This will start up a wizard-like command line utility that will walk you through creating a package.


1 Answers

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?

like image 99
Myrne Stol Avatar answered Sep 26 '22 08:09

Myrne Stol