使用Node Js测量处理时间?

时间:2018-02-13 14:09:44

标签: javascript node.js performance

我想做以下事情:

console.time("processA");
for(let i; i < 10000; i++) {
// Just to simulate the process
}
console.timeEnd("processA");

但我希望捕捉时间结束并使用我自己的信息记录器。

是否可以处理timeEnd的控制台输出?

如何在nodejs中测量进程的时间间隔?

4 个答案:

答案 0 :(得分:6)

由于您定位的是nodejs,因此您可以docs

中所述使用process.hrtime
  

process.hrtime()方法在[秒,纳秒]元组数组中返回当前的高分辨率实时,其中纳秒是实时的剩余部分,无法以第二精度表示。

因此,您可以测量高达纳秒的时间,console.time无法测量的时间,正如您在示例console.timeDate差异度量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";