window.performance.now()相当于nodejs?
我认为这个问题很简单。
我正在寻找类似于nodejs V8引擎中的window.performance.now()的东西。
现在我只是使用: –
var now = Date.now(); //do some processing.. console.log("time elapsed:", Date.now() - now);
但是,我读了window.performance.now()比使用date更准确,因为这里定义了什么。
我只想提到,作者在浏览器中给定时间API的偏好的三个原因似乎并不直接适用于节点的情况,第四,Javscript时间的不准确性引用了2008年的一篇文章,我强烈build议不要依赖关于Javascript性能细节的老版本,尤其是考虑到所有引擎支持“HTML5”应用程序的最新性能改进。
但是,在回答你的问题时,你应该看看process.hrtime()
更新: present
软件包(通过npm install present
)提供了一些糖周围hrtime
如果你喜欢它。
这里是process.hrtime()
的快捷方式,返回的是毫秒而不是微秒:
function clock(start) { if ( !start ) return process.hrtime(); var end = process.hrtime(start); return Math.round((end[0]*1000) + (end[1]/1000000)); }
用法:
var start = clock(); // do some processing that takes time var duration = clock(start); console.log("Took "+duration+"ms");
会输出类似“Took 200ms”
关于什么?
console.time('FooTimer'); // do the work console.timeEnd('FooTimer');
Node v8.5.0增加了Performance Timing API ,其中包括了performance#now()
的performance#now()
,例如
const { performance } = require('perf_hooks'); console.log('performance', performance.now());
下面是一个带有process.hrtime()的Typescript版本,基于NextLocal的回答:
class Benchmark { private start = process.hrtime(); public elapsed(): number { const end = process.hrtime(this.start); return Math.round((end[0] * 1000) + (end[1] / 1000000)); } } export = Benchmark;
用法:
import Benchmark = require("./benchmark"); const benchmark = new Benchmark(); console.log(benchmark.elapsed());