NiL*_*iLL 84 javascript v8 node.js
如何在Node.js中获得最准确的时间戳?
ps我的Node.js版本是0.8.X,node-microtime扩展名对我不起作用(安装时崩溃)
Myr*_*tol 164
在Node.js中,"高分辨率时间"通过process.hrtime.它返回一个数组,第一个元素是以秒为单位的时间,第二个元素是剩余的纳秒数.
要以微秒为单位获取当前时间,请执行以下操作:
var hrTime = process.hrtime()
console.log(hrTime[0] * 1000000 + hrTime[1] / 1000)
Run Code Online (Sandbox Code Playgroud)
(感谢itaifrenkel指出上述转换中的错误.)
在现代浏览器中,具有微秒精度的时间可用performance.now.有关文档,请参阅https://developer.mozilla.org/en-US/docs/Web/API/Performance/now.
我已经为Node.js实现了这个函数的实现,process.hrtime如果您只想计算程序中两点之间的时间差,则相对难以使用.见http://npmjs.org/package/performance-now.根据规范,此函数以毫秒为单位报告时间,但它是具有亚毫秒精度的浮点数.
在此模块的2.0版中,报告的毫秒数与启动节点进程的时间相关(Date.now() - (process.uptime() * 1000)).如果需要类似的时间戳,则需要将其添加到结果中Date.now().另请注意,您应该重新计算Date.now() - (process.uptime() * 1000).两者都非常不可靠Date.now,process.uptime无法进行精确测量.
要获得以微秒为单位的当前时间,您可以使用类似的东西.
var loadTimeInMS = Date.now()
var performanceNow = require("performance-now")
console.log((loadTimeInMS + performanceNow()) * 1000)
Run Code Online (Sandbox Code Playgroud)
Nie*_*sol 93
new Date().getTime()?这为您提供了一个以毫秒为单位的时间戳,这是JS给您的最准确的时间戳.
更新:正如vaughan所述,process.hrtime()在Node.js中可用 - 它的分辨率是纳秒,因此它的分辨率要高得多,这并不意味着它必须更精确.
PS.:为了更清楚,在[秒,纳秒]内process.hrtime()返回Array包含当前高分辨率实时的元组
Abd*_*UMI 18
now('milli'); // 120335360.999686
now('micro') ; // 120335360966.583
now('nano') ; // 120335360904333
Run Code Online (Sandbox Code Playgroud)
已知的now是:
const now = (unit) => {
const hrTime = process.hrtime();
switch (unit) {
case 'milli':
return hrTime[0] * 1000 + hrTime[1] / 1000000;
case 'micro':
return hrTime[0] * 1000000 + hrTime[1] / 1000;
case 'nano':
return hrTime[0] * 1000000000 + hrTime[1];
default:
return now('nano');
}
};
Run Code Online (Sandbox Code Playgroud)
jcu*_*bic 11
您还可以使用在 NodeJS 和浏览器中都有效的性能 API:
var start = performance.timing ?
performance.timing.navigationStart :
performance.timeOrigin;
var time = (performance.now() + start) * 1000;
Run Code Online (Sandbox Code Playgroud)
Performance API 以浮点数存储值,小数部分为微秒。
编辑:使用现代 JavaScript,您可以使用以下代码:
const start = performance?.timing ?? performance.timeOrigin;
const time = (performance.now() + start) * 1000;
Run Code Online (Sandbox Code Playgroud)
BigInt从Node.js 10.7.0开始支持该数据类型。(另请参见博客文章公告)。对于这些受支持的Node.js版本,该process.hrtime([time])方法现在被视为“旧版”,由该process.hrtime.bigint()方法代替。
该方法的
bigint版本会在中process.hrtime()返回当前的高分辨率实时图像bigint。
const start = process.hrtime.bigint();
// 191051479007711n
setTimeout(() => {
const end = process.hrtime.bigint();
// 191052633396993n
console.log(`Benchmark took ${end - start} nanoseconds`);
// Benchmark took 1154389282 nanoseconds
}, 1000);
Run Code Online (Sandbox Code Playgroud)
tl; dr
process.hrtime.bigint()process.hrtime()还有https://github.com/wadey/node-microtime:
> var microtime = require('microtime')
> microtime.now()
1297448895297028
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
113005 次 |
| 最近记录: |