我认为这个问题是直截了当的。
我正在寻找类似于 nodejs V8 引擎中的 window.performance.now() 的东西。
现在我只是在使用:-
var now = Date.now();
//do some processing..
console.log("time elapsed:", Date.now() - now);
但是,我读到 window.performance.now() 比使用日期准确得多,因为这里定义了什么。
我认为这个问题是直截了当的。
我正在寻找类似于 nodejs V8 引擎中的 window.performance.now() 的东西。
现在我只是在使用:-
var now = Date.now();
//do some processing..
console.log("time elapsed:", Date.now() - now);
但是,我读到 window.performance.now() 比使用日期准确得多,因为这里定义了什么。
Node v8.5.0 增加了Performance Timing API,其中包括performance#now()
,例如
const {
performance
} = require('perf_hooks');
console.log('performance', performance.now());
我只想提一下,作者给出的浏览器中计时 API 的偏好的三个原因似乎并不直接适用于节点情况,第四个,Javscript 时间的不准确,引用了 2008 年的一篇文章,我强烈警告不要依赖关于 Javascript 性能细节的旧材料,特别是考虑到最近一轮所有引擎为支持“HTML5”应用程序所做的性能改进。
但是,在回答您的问题时,您应该查看process.hrtime()
更新:如果您愿意,该present
软件包(可通过 获取npm install present
)提供一些糖。hrtime
注意:从Node 8.5.0 版本开始,可以使用performance.now()
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');
“该方法返回
process.uptime()
当前 Node.js 进程已运行的秒数。返回值包括几分之一秒。用于
Math.floor()
获得 整秒。”
const nemo = ['nemo'];
function findNemo(array) {
let start_time = process.uptime();
for (let iteration = 0; iteration < array.length; iteration++) {
if (array[iteration] === 'nemo') {
console.log("Found Nemo");
}
}
let end_time = process.uptime();
console.log("For loop took this much time: ", end_time - start_time);
}
findNemo(nemo);
这是基于NextLocal 的回答的带有process.hrtime()的 Typescript 版本:
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());
总结和避免使用perf_hooks
const performance = {
now: function(start) {
if ( !start ) return process.hrtime();
var end = process.hrtime(start);
return Math.round((end[0]*1000) + (end[1]/1000000));
}
}
console.log('performance', performance.now());
此方法在 nodejs 的 8.5.0 版本中出现https://nodejs.org/api/perf_hooks.html#perf_hooks_performance_measurement_apis