Is there any way to get current time in nanosecond

2019-01-15 05:10发布

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

6条回答
Animai°情兽
2楼-- · 2019-01-15 05:42

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.

查看更多
欢心
3楼-- · 2019-01-15 05:44

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".

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-01-15 05:44

Yes! Try the excellent sazze's nano-time

let now = require('nano-time');
now(); // '1476742925219947761' (returns as string due to JS limitation)
查看更多
祖国的老花朵
5楼-- · 2019-01-15 05:45

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".

查看更多
干净又极端
7楼-- · 2019-01-15 06:01

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);
}

查看更多
登录 后发表回答