jua*_*cia 5 javascript performance node.js
我要执行以下操作:
console.time("processA");
for(let i; i < 10000; i++) {
// Just to simulate the process
}
console.timeEnd("processA");
Run Code Online (Sandbox Code Playgroud)
但我想记录时间并使用自己的信息记录器。
是否可以处理timeEnd的控制台输出?
如何在Node.js中测量进程的时间间隔?
Dee*_*pal 12
从 Node v8.5 开始,您可以使用浏览器等效项performance.now(),这比直接输出以毫秒为单位的时间更容易使用process.hrtime,因此您不必像process.hrtime
const { performance } = require("perf_hooks");
const start = performance.now();
doSomething();
const end = performance.now();
console.log(`time taken: ${end - start}ms`);
Run Code Online (Sandbox Code Playgroud)
您可以从Node.js 文档的 Performance API 中找到更多信息。
由于您的目标是nodejs,因此可以process.hrtime按照文档中的说明使用
process.hrtime()方法以[秒,纳秒]元组数组返回当前的高分辨率实时,其中纳秒是实时的剩余部分,无法以秒精度表示。
所以,你可以测量计时高达纳秒,这东西console.time不能,因为你可以在你的例子中看到console.time或Date差别措施0。
例如:
const NS_PER_SEC = 1e9;
const MS_PER_NS = 1e-6
const time = process.hrtime();
for (let i; i < 10000; i++) {
// Just to simulate the process
}
const diff = process.hrtime(time);
console.log(`Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`);
console.log(`Benchmark took ${ (diff[0] * NS_PER_SEC + diff[1]) * MS_PER_NS } milliseconds`);
Run Code Online (Sandbox Code Playgroud)
由于我在多个地方使用计时器,因此我根据Alex 的答案编写了一个简单的类:
const t = new Timer('For Loop')
// your code
t.runtimeMs() // => 1212.34
t.runtimeMsStr() // => 'For Loop took 1232.34 milliseconds'
Run Code Online (Sandbox Code Playgroud)
这是代码:
const t = new Timer('For Loop')
// your code
t.runtimeMs() // => 1212.34
t.runtimeMsStr() // => 'For Loop took 1232.34 milliseconds'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3473 次 |
| 最近记录: |