我想做以下事情:
console.time("processA");
for(let i; i < 10000; i++) {
// Just to simulate the process
}
console.timeEnd("processA");
但我希望捕捉时间结束并使用我自己的信息记录器。
是否可以处理timeEnd的控制台输出?
如何在nodejs中测量进程的时间间隔?
答案 0 :(得分:6)
由于您定位的是nodejs,因此您可以docs
中所述使用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`);
答案 1 :(得分:3)
var startTime = new Date();
for(let i; i < 10000; i++) {
// Just to simulate the process
}
var endTime = new Date() - startTime;
您将获得完成操作所需的总时间
答案 2 :(得分:1)
由于我在多个地方使用计时器,因此我基于https://php.net/manual/en/migration71.incompatible.php编写了一个简单的类:
c.execute("SELECT TOTAL(%s) FROM expense" % list2[i])
代码如下:
const t = new Timer('For Loop')
// your code
t.runtimeMs() // => 1212.34
t.runtimeMsStr() // => 'For Loop took 1232.34 milliseconds'
答案 3 :(得分:0)
请参阅此处https://alligator.io/js/console-time-timeend/
var begin=console.time('t');
for(let i; i < 100000; i++) {
// Just to simulate the process
}
var end= console.timeEnd('t');
var timeSpent=(end-begin) / 1000 + "secs";