我想知道該程序完全完成所花費的時間。我有這段代碼:
console.log(`Ran ${ran} equations in ${console.timeEnd()}`)
但我沒有得到預期的輸出,即:
Ran X equations in 33.099ms // eg
相反我得到
default: 33.099ms
Ran X Equations in undefined
請注意,我沒有給我console.time()貼上標簽。
我怎樣才能達到我的預期輸出?
uj5u.com熱心網友回復:
console.timeEnd不回傳任何東西;如您所知,它是控制臺的一部分。因為console.timeEnd以帶小數位的毫秒計數(與 不同Date.now()),您將獲得的最接近的結果是使用performance.now(). 我們可以創建一個自定義時間函式:
class Time {
constructor() {
this.time = performance.now();
}
end() {
return (performance.now() - this.time).toFixed(3); // round number to lower decimal precision, like console.time()
}
}
const time = new Time();
console.time("Console measurement");
let dummyVar = 0;
for(let i = 0; i < 1000000; i ) {
// do some time consuming task
dummyVar = i;
}
console.log("Custom measurement:", time.end() "ms");
console.timeEnd("Console measurement");
我故意回傳一個數字而不是字串(末尾帶有“ms”),以便您可以更好地使用它。顯然,如果您想表示 的確切輸出console.timeEnd(),只需附加 "ms"到 中的運算式即可Time#end:
顯示代碼片段
class Time {
constructor() {
this.time = performance.now();
}
end() {
return (performance.now() - this.time).toFixed(3) "ms";
}
}
const time = new Time();
// dummy example
setTimeout(() => console.log(`Ran X equations in ${time.end()}`), Math.floor(Math.random() * 100));
uj5u.com熱心網友回復:
console.timeEnd()回傳undefined,而不是它記錄的內容。要非常接近所需的輸出,請使用描述性字串標記計時器...
const ran = 4; // you'll need to know ran before starting the timer
const label = `Ran ${ran} equations in`;
console.time(label);
// do some time consuming stuff
alert('wait a sec, then press ok')
console.timeEnd(label);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/537326.html
下一篇:如何唯一陣列物件值?
