![](/img/trans.png)
[英]JS performance.now() and console.time() inaccurate in Nodejs?
[英]console.time() vs performance.now() in Node.js
我在網上找到了幾篇關於如何在 Node.js 中測量代碼性能的文章和問題。 但我得到的結果相差大約兩倍,具體取決於測量工具。 目標 function 是:
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.")
這里我想知道有問題的數組中是否有兩個數字,把它們相加,我得到第二個參數叫做function。 這兩種方法我是獨立使用的,只是注釋掉代碼的對應部分。 console.time()
給出平均 0.300 毫秒的性能得分console.time 結果
和performance.now()
給出 0.170ms performance.now 結果
請幫助我理解為什么這兩種方法會給出不同的結果(幾乎翻倍)? 我正在使用 Node v15、CPU Core i5、8GB RAM、Win10。
如果您將測量值放在一個小循環中,您會發現它們幾乎與自身不一致。
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()
1000 萬次:
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 更重要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.