NodeJS 节点. js中的控制台.time()与performance.now()

gpfsuwkq  于 2023-03-08  发布在  Node.js
关注(0)|答案(1)|浏览(147)

我在互联网上找到了几篇文章和一些关于如何测量Node中代码性能的问题。但是我得到的结果相差大约两倍,这取决于测量工具。目标函数是:

let arr = [75, 283, 361, 168, 23, 489, 421, 95, 72, 380, 384, 470, 235, 465, 276, 26, 364, 416, 373, 184, 211, 239, 485, 18, 19, 252, 447, 6, 291, 324, 497, 352,
458, 201, 238, 116, 333, 163, 207, 417, 340, 431, 5, 269, 258, 178, 182, 295, 257, 434, 37, 372, 154, 223, 313, 80, 71, 229, 379, 181, 396, 281, 491, 58, 254,
359, 79, 175, 143, 214, 217, 148, 393, 246, 34, 166, 251, 381, 413, 180, 338, 
442, 494, 378, 123, 118, 395, 446, 459, 472, 457, 51, 127, 351, 389, 157, 260, 
370, 405, 346]

const { performance } = require("perf_hooks")

function summBrute(arr, k) {
    
    for(let i = 0; i < arr.length; i++) {
        for(let j = i + 1; j < arr.length; j++) {
           if(arr[i] + arr[j] == k) {
               return true;
           }
        }
    }
    return false;
    
}

测量方法为:

console.time('summBrute')
summBrute(arr, 394)
console.timeEnd('summBrute')

var t0 = performance.now()
summBrute(arr, 394)  //
var t1 = performance.now()
console.log("Call to summBrute took " + (t1 - t0) + " milliseconds.")

在这里,我想找出数组中是否有两个数字,将它们相加,得到被调用函数的第二个参数。我独立使用这两个方法,只是注解掉代码的相应部分。console.time()给出的平均性能得分为0.300ms console.time result
并且performance.now()给出0.170毫秒performance.now result
请帮助我理解为什么这两种方法给予不同的结果(几乎翻了一番)?我使用的是节点v15,CPU核心i5,8GB内存,Win10。

3pvhb19x

3pvhb19x1#

如果你把这些测量值放进一个小循环中,你会看到它们几乎与自己不一致。

for(let i=0;i<5;i++){

console.time('summBrute')
summBrute(arr, 394)
console.timeEnd('summBrute')

var t0 = performance.now()
summBrute(arr, 394)  //
var t1 = performance.now()
console.log("Call to summBrute took " + (t1 - t0) + " milliseconds.")

}

生产

summBrute: 0.234ms
Call to summBrute took 0.1938999891281128 milliseconds.
summBrute: 0.171ms
Call to summBrute took 0.13520002365112305 milliseconds.
summBrute: 0.107ms
Call to summBrute took 0.1332000494003296 milliseconds.
summBrute: 0.095ms
Call to summBrute took 0.10259997844696045 milliseconds.
summBrute: 1.385ms
Call to summBrute took 0.10839998722076416 milliseconds.

它们几乎是随机数,没有用。
但是如果我调用summBrute()一千万次:

for(let i=0;i<5;i++){

console.time('summBrute')
for(let j=0;j<10000000;j++)
  summBrute(arr, 394)
console.timeEnd('summBrute')

var t0 = performance.now()
for(let j=0;j<10000000;j++)
  summBrute(arr, 394)  //
var t1 = performance.now()
console.log("Call to summBrute took " + (t1 - t0) + " milliseconds.")

}

结果不再依赖于我的电脑的情绪,变得更加一致:

summBrute: 16.369s
Call to summBrute took 16184.267899990082 milliseconds.
summBrute: 15.643s
Call to summBrute took 15852.86260008812 milliseconds.
summBrute: 16.355s
Call to summBrute took 15942.392500042915 milliseconds.
summBrute: 16.190s
Call to summBrute took 16314.965299963951 milliseconds.
summBrute: 16.523s
Call to summBrute took 16744.983800053596 milliseconds.

它仍然有一个几乎半秒的差距,但很明显,平均(1000万次呼叫)约为16秒,因此一次呼叫约为0.016毫秒,这显然不是任何单独呼叫所测量的。
TL;DR:时间就是时间,衡量什么比选择计时器API重要得多。

相关问题