window.performance.now()在nodejs中等价?

shr*_*iek 57 javascript node.js navigation-timing-api

我认为问题是直截了当的.

我正在寻找类似于nodejs V8引擎中的window.performance.now()的东西.

现在我只是使用: -

var now = Date.now();
//do some processing..
console.log("time elapsed:", Date.now() - now);
Run Code Online (Sandbox Code Playgroud)

但是,我读到window.performance.now()比使用日期要准确得多,因为这里定义了什么.

Gaj*_*jus 63

Node v8.5.0添加了Performance Timing API,其中包括performance#now()例如

const {
  performance
} = require('perf_hooks');

console.log('performance', performance.now());
Run Code Online (Sandbox Code Playgroud)

  • 或 ```import { Performance } from "perf_hooks";``` 对于模块 (.mjs) (3认同)

bar*_*son 39

我只想提一下,作者在浏览器中偏好定时API的三个原因似乎并不直接适用于节点情况,第四个是Javscript时间的不准确,引用了2008年的一篇文章,我强烈建议不要依赖有关Javascript性能细节的旧材料,特别是考虑到最近一轮性能改进所有引擎都支持"HTML5"应用程序.

但是,在回答你的问题时,你应该看一下 process.hrtime()

更新:present包装(可通过npm install present)提供一些糖,hrtime如果你喜欢它.

  • 显然,原始问题中发布的链接的作者。问题是上下文。添加它是一种冗余,而不是上下文。 (2认同)

jag*_*oft 30

这是一个process.hrtime()返回毫秒而不是微秒的快捷方式:

function clock(start) {
    if ( !start ) return process.hrtime();
    var end = process.hrtime(start);
    return Math.round((end[0]*1000) + (end[1]/1000000));
}
Run Code Online (Sandbox Code Playgroud)

用法:

var start = clock();
// do some processing that takes time
var duration = clock(start);
console.log("Took "+duration+"ms");
Run Code Online (Sandbox Code Playgroud)

输出类似"Took 200ms"的东西


ten*_*its 14

关于什么?

console.time('FooTimer');
// do the work
console.timeEnd('FooTimer');
Run Code Online (Sandbox Code Playgroud)