有没有办法使用 JavaScript 获取当前时间(以纳秒为单位)?
所以,我知道我可以使用 JavaScript 获取当前时间(以毫秒为单位)。但是,是否有可能以纳秒为单位获取当前时间?
So, I know I can get current time in milliseconds using JavaScript. But, is it possible to get the current time in nanoseconds instead?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
在大多数浏览器中使用以下方法实现微秒精度:
另请参阅:
Achieve microsecond accuracy in most browsers using:
See also:
基于 Jeffery 的答案,要获得绝对时间戳(正如OP想要的那样),代码将是:
结果以毫秒为单位,但据报道是一个浮点值“精确到千分之一毫秒”。
Building on Jeffery's answer, to get an absolute time-stamp (as the OP wanted) the code would be:
result is in millisecond units but is a floating-point value reportedly "accurate to one thousandth of a millisecond".
自 UNIX 纪元以来的毫秒数,采用微秒分辨率。
performance.timing.navigationStart
已弃用!请改用以下内容:规范中的相关引用
请注意,实际上,出于安全原因(防止旁道攻击),它并不那么准确
Milliseconds since the UNIX epoch, with the microseconds resolution.
performance.timing.navigationStart
has been deprecated! Use the following instead:Relevant quotes from the specification
Note that actually it is not that accurate for security reasons (to prevent side-channel attacks)
在 Node.js 这样的服务器端环境中,您可以使用以下函数来获取纳秒级的时间
也以类似的方式获取微秒:
In Server side environments like Node.js you can use the following function to get time in nanosecond
Also get micro seconds in a similar way as well:
是的!尝试一下出色的 sazze 的 nano-time
Yes! Try the excellent sazze's nano-time
不。您不可能在 JavaScript 层获得纳秒级的精度。
如果您想对一些非常快速的操作进行基准测试,请将其放入一个运行数千次的循环中。
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.
JavaScript 以毫秒为单位记录时间,因此您无法获得如此精确的时间。 smart-aleck 的答案是“乘以 1,000,000”。
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".
我一直在寻找与此类似的东西,这就是我最终想到的,它可能不是 100% 准确,但它是我能得到的最接近的。
var precision = 3;
var timestring = new Date().toLocaleTimeString() + "." + (((性能.now() + 性能.timeOrigin)) / 1000).toFixed(精度).toString().split(".")[1]);
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]);