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
| 瀏覽器 | 支援版本 | 備註 |
|---|---|---|
| Chrome | 2.0+ | 完整支援 |
| Firefox | 10.0+ | 早期需 Firebug 外掛 |
| Safari | 4.0+ | 完整支援 |
| Edge | 12+ | 完整支援 |
| IE | 11 | IE10- 不支援,可用 Firebug Lite |
| Node.js | 0.10+ | 完整支援 |
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
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');
}
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 面板** 提供更詳細分析:
// 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');
if (process.env.NODE_ENV !== 'production')'user-login-validate'console.group 組織輸出| 工具 | 精度 | 適用場景 | 侵入性 |
|---|---|---|---|
console.time | 亞毫秒 | 快速除錯、區塊測量 | 低 (一行代碼) |
performance.now() | 微秒級 | 精密測量、非同步、Worker | 低 |
| Performance API | 微秒級 | 完整生命週期、資源載入 | 中 |
| DevTools Performance | 微秒級 | 深度分析、火焰圖、記憶體 | 零 (外部工具) |
| benchmark.js | 統計學 | 函式基準測試、統計顯著性 | 高 (引入庫) |
console.time()/timeEnd() 是零依賴、零配置、即時可用的效能測量利器。善用標籤管理多計時器、timeLog() 追蹤階段、配合 DevTools 深度分析,能大幅提升效能調優效率。記得生產環境移除或條件編譯。