萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 效能測量利器:console.time() 與 console.timeEnd() 完整教學

console.time() 和 console.timeEnd() 是瀏覽器內建的高精度計時 API,適合快速測量程式碼區塊執行時間,無需引入外部庫。本文詳細說明用法、參數配對機制、瀏覽器支援度與進階效能分析技巧。

基本用法

console.time('timer-label'); // 啟動計時器,標籤為 'timer-label'

// 要測量的程式碼
function heavyComputation() {
    var x = 4.237, y = 0;
    for (var i = 0; i < 100000000; i++) {
        y += x * x;
    }
    return y;
}

heavyComputation();

console.timeEnd('timer-label'); // 停止並輸出:timer-label: 1797.123ms

參數配對機制

  • 相同 **標籤字串** 的 time() 和 timeEnd() 會配對
  • 可同時運行多個計時器,使用不同標籤
  • 標籤區分大小寫,建議使用語意化名稱
console.time('total');
console.time('loop');
for (var i=0; i<1e6; i++) {}
console.timeEnd('loop'); // loop: 12.345ms

console.time('dom');
document.body.appendChild(document.createElement('div'));
console.timeEnd('dom');  // dom: 0.456ms

console.timeEnd('total'); // total: 13.123ms (含上述兩段)

進階:console.timeLog() 中間紀錄

console.time('process');
step1();
console.timeLog('process'); // 輸出經過時間,計時器持續運行
step2();
console.timeLog('process');
step3();
console.timeEnd('process');

輸出範例:

process: 10.5ms
process: 25.8ms
process: 42.1ms

瀏覽器支援度

瀏覽器支援版本備註
Chrome2.0+完整支援
Firefox10.0+早期需 Firebug 外掛
Safari4.0+完整支援
Edge12+完整支援
IE11IE10- 不支援,可用 Firebug Lite
Node.js0.10+完整支援

實戰應用場景

1. 函式效能比較

function fibRecursive(n) { return n < 2 ? n : fibRecursive(n-1) + fibRecursive(n-2); }
function fibIterative(n) { 
    var a=0, b=1; 
    for(var i=0;i

2. 非同步操作測量

async function fetchUserData() {
    console.time('api-total');
    
    console.time('fetch-user');
    var user = await fetch('/api/user').then(r=>r.json());
    console.timeEnd('fetch-user');
    
    console.time('fetch-posts');
    var posts = await fetch('/api/posts').then(r=>r.json());
    console.timeEnd('fetch-posts');
    
    console.timeEnd('api-total');
}

3. 記憶體配合測量

console.time('memory-test');
console.memory && console.log('開始:', console.memory.usedJSHeapSize);

var bigArray = new Array(1000000).fill('x');

console.memory && console.log('建立後:', console.memory.usedJSHeapSize);
console.timeEnd('memory-test');

效能面板進階分析

DevTools **Performance 面板** 提供更詳細分析:

  • 火焰圖 找出熱點函式
  • Call Tree 依呼叫關係統計耗時
  • Bottom-Up (Heavy) 找出自耗時最久函式
  • 記憶體堆疊快照比較洩漏

Node.js 環境補充

// Node.js 同樣支援
console.time('file-read');
fs.readFileSync('large-file.txt');
console.timeEnd('file-read');

// 高精度替代:process.hrtime.bigint()
var start = process.hrtime.bigint();
// ...操作
var end = process.hrtime.bigint();
console.log('耗時 (奈秒):', Number(end - start) / 1e6, 'ms');

最佳實務與注意事項

  1. 開發/除錯專用:生產環境建議移除或包裝在 if (process.env.NODE_ENV !== 'production')
  2. 避免過度測量:頻繁呼叫 console API 本身有開銷
  3. 標籤命名規範:模組-功能-階段,如 'user-login-validate'
  4. 配合 console.group 組織輸出

替代方案比較

工具精度適用場景侵入性
console.time亞毫秒快速除錯、區塊測量低 (一行代碼)
performance.now()微秒級精密測量、非同步、Worker低
Performance API微秒級完整生命週期、資源載入中
DevTools Performance微秒級深度分析、火焰圖、記憶體零 (外部工具)
benchmark.js統計學函式基準測試、統計顯著性高 (引入庫)

總結

console.time()/timeEnd() 是零依賴、零配置、即時可用的效能測量利器。善用標籤管理多計時器、timeLog() 追蹤階段、配合 DevTools 深度分析,能大幅提升效能調優效率。記得生產環境移除或條件編譯。

copyright © 萬盛學電腦網 all rights reserved