Is there any way to get current time in nanoseconds using JavaScript?
Asked Answered
E

8

86

So, I know I can get current time in milliseconds using JavaScript. But, is it possible to get the current time in nanoseconds instead?

Extraterritoriality answered 14/5, 2011 at 15:29 Comment(0)
N
96

Achieve microsecond accuracy in most browsers using:

window.performance.now()

See also:

Naughton answered 9/8, 2012 at 18:40 Comment(5)
The 'webkit' prefix was removed around Chrome 24. developer.mozilla.org/en-US/docs/Web/API/…Stevana
Note that window.performance.now() returns the time relative to the navigationStart of the page rather than to the UNIX epoch. See my answer below for code snippet for current time.Negron
Yet, microseconds are not nanoseconds, so performance.now() is useless here.Test
Apparently browsers don’t actually return nanosecond precision due to security considerations, according to the hint on the MDN site you linked: “[B]rowsers currently round the results to varying degrees. […] Some browsers may also slightly randomize the timestamp.”Amphibole
"The performance.now() method returns a DOMHighResTimeStamp, measured in milliseconds", according to the link you posted. Milliseconds are not nanoseconds.Doorpost
N
12

Building on Jeffery's answer, to get an absolute time-stamp (as the OP wanted) the code would be:

var TS = window.performance.timing.navigationStart + window.performance.now();

result is in millisecond units but is a floating-point value reportedly "accurate to one thousandth of a millisecond".

Negron answered 24/12, 2015 at 22:48 Comment(1)
WARNING performance.timing.navigationStart has been deprecated.Hades
M
11

Milliseconds since the UNIX epoch, with the microseconds resolution.

performance.timing.navigationStart has been deprecated! Use the following instead:

(performance.now() + performance.timeOrigin)

Relevant quotes from the specification

This specification defines an API that provides the time origin, and current time in sub-millisecond resolution, such that it is not subject to system clock skew or adjustments.

The timeOrigin attribute MUST return a DOMHighResTimeStamp representing the high resolution time of the time origin timestamp for the relevant global object of the Performance object.

The time origin timestamp is the high resolution time value at which time origin is zero.

The time origin is the time value from which time is measured

The now() method MUST return the current high resolution time.

The current high resolution time is the high resolution time from the time origin to the present time (typically called “now”).


Note that actually it is not that accurate for security reasons (to prevent side-channel attacks)

This specification defines an API that provides sub-millisecond time resolution, which is more accurate than the previously available millisecond resolution exposed by DOMTimeStamp. However, even without this new API an attacker may be able to obtain high-resolution estimates through repeat execution and statistical analysis. To ensure that the new API does not significantly improve the accuracy or speed of such attacks, the minimum resolution of the DOMHighResTimeStamp type should be inaccurate enough to prevent attacks: the current minimum recommended resolution is no less than 5 microseconds and, where necessary, should be set higher by the User Agent to address privacy and security concerns due to architecture or software constraints, or other considerations.

Maricamarice answered 4/5, 2020 at 13:13 Comment(2)
This is the closest as you can possibly get.Unparalleled
Maybe you should mention that it returns using decimals. So it is still milliseconds, so we don't have to go through that error.Mixon
R
10

In Server side environments like Node.js you can use the following function to get time in nanosecond

function getNanoSecTime() {
  var hrTime = process.hrtime();
  return hrTime[0] * 1000000000 + hrTime[1];
}

Also get micro seconds in a similar way as well:

function getMicSecTime() {
  var hrTime = process.hrtime();
  return hrTime[0] * 1000000 + parseInt(hrTime[1] / 1000);
}
Religiose answered 27/2, 2016 at 21:22 Comment(2)
This does NOT return the CURRENT timestamp when using Node 7.4.0 and 7.5.0.Sarnoff
I happened to see this in api of process.hrtime: "These times are relative to an arbitrary time in the past, and not related to the time of day and therefore not subject to clock drift. The primary use is for measuring performance between intervals".Abhor
S
6

Yes! Try the excellent sazze's nano-time

let now = require('nano-time');
now(); // '1476742925219947761' (returns as string due to JS limitation)
Sarnoff answered 17/2, 2017 at 4:2 Comment(2)
NB -- for node only -- uses process.hrtime() (@TahsinTurkoz), and then calculates an absolute time from that.Merlon
After installing nano-time, this gives me Uncaught TypeError: process.hrtime is not a functionRoxanneroxburgh
P
5

No. There is not a chance you will get nanosecond accuracy at the JavaScript layer.

If you're trying to benchmark some very quick operation, put it in a loop that runs it a few thousand times.

Perfectionist answered 14/5, 2011 at 15:32 Comment(9)
+1 ...and why would you want to? If it needs to be that precise it should probably not be JavaScript in the first place. PS: Hey, mod: deleting flame comments should leave the valid comments intact. Just an idea.Fez
Do you know who delete all the comments?Fez
I know, necropost. I just did. start millisecond timer, run the function 10,000,000 times, stop millisecond timer, and divide the execution time by 10,000,000. I was timing the timer itself to calibrate it, as running the timer and typecasting/concatenating the output takes time. Takes 3 microseconds on my computer, give or take about 200 nanoseconds.Molecule
Of course, knowing the execution time down to the last 0.00000001 seconds isn't really necessary; unless that functions going to run 1,000,000,000 times.Molecule
@evandentremont Microseconds are an entire three orders of magnitude above nanoseconds!Perfectionist
Resurrecting this discussion, benchmarks aren't the only use case for time precision. There are some algorithms where it may be needed, and if I want to run it on a browser, JS is a necessity.Extraterritoriality
@EduardoMelo For example, LRU replacement in a page fault simulator (a project I'm working on now). Millisecond precision isn't good enough because the code runs too fast and the timestamp on my pages all have the same values per 1k pages or so...Cobham
@ChrisCirefice There’s no need to use wall clock time for paging algorithms. Use a simple counter instead.Amphibole
@Amphibole That's what I ended up doing ;)Cobham
M
2

JavaScript records time in milliseconds, so you won't be able to get time to that precision. The smart-aleck answer is to "multiply by 1,000,000".

Matelote answered 14/5, 2011 at 15:33 Comment(1)
This is actually exactly what I wanted, I don't actually care about the nanosecond time just need a Date to go into the correct format ;)Diagnostician
M
0

I was looking for something similar to this, this is what i came up with in the end, it may not be 100% accurate but its the closest i could get.

var precision = 3;

var timestring = new Date().toLocaleTimeString() + "." + (((performance.now() + performance.timeOrigin)) / 1000).toFixed(precision).toString().split(".")[1]);

for (i=0;i<1000;i++){
  var precision = 3;
  var timestring = new Date().toLocaleTimeString() + "." + (((performance.now() + performance.timeOrigin)) / 1000).toFixed(precision).toString().split(".")[1];
  var newEl = document.createElement('div');
  
  newEl.innerHTML = timestring;
  document.getElementById("timestamps").appendChild(newEl);
}
<p>Timstamps:</p>
<div id="timestamps"></div>
Montalvo answered 13/6, 2024 at 9:56 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.