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

余生长醉 提交于 2019-11-26 18:27:42

问题


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


回答1:


Achieve microsecond accuracy in most browsers using:

window.performance.now()

See also:

  • https://developer.mozilla.org/en-US/docs/Web/API/Performance.now()
  • http://www.w3.org/TR/hr-time/



回答2:


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




回答3:


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



回答4:


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.




回答5:


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




回答6:


Yes! Try the excellent sazze's nano-time

let now = require('nano-time');
now(); // '1476742925219947761' (returns as string due to JS limitation)


来源:https://stackoverflow.com/questions/6002808/is-there-any-way-to-get-current-time-in-nanoseconds-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!