效能分析與除錯時,常需測量特定程式區塊的執行耗時。本文提供 Timer 類別,支援多標記獨立計時、微秒級精度、自動格式化輸出,適合插桿式效能分析。
microtime() 實現浮點數秒級測量。start()、end()、getTime()、printTime()。<?php
class Timer {
private $_start = [];
private $_end = [];
private $_default_key = 'Timer';
private $_prefix = 'Timer_';
public function start($key = '') {
$flag = $this->getKey($key);
$this->_start[$flag] = $this->getMicrotime();
}
public function end($key = '') {
$flag = $this->getKey($key);
$this->_end[$flag] = $this->getMicrotime();
}
public function getTime($key = '') {
$flag = $this->getKey($key);
if (isset($this->_end[$flag]) && isset($this->_start[$flag])) {
return (float)($this->_end[$flag] - $this->_start[$flag]);
}
return 0;
}
public function printTime($key = '') {
$label = $key === '' ? $key : $key . ' ';
printf("%srun time %f ms\n", $label, $this->getTime($key) * 1000);
}
private function getKey($key = '') {
return $key === '' ? $this->_default_key : $this->_prefix . $key;
}
private function getMicrotime() {
list($usec, $sec) = explode(' ', microtime());
return (float)$usec + (float)$sec;
}
}
?>
<?php
require 'Timer.class.php';
$timer = new Timer();
$timer->start(); // 全域計時開始
$timer->start('program1'); // 區塊 1 計時
usleep(mt_rand(100000, 500000)); // 模擬耗時操作
$timer->end('program1');
$timer->printTime('program1'); // 輸出:program1 run time 163.285971 ms
$timer->start('program2');
usleep(mt_rand(100000, 500000));
$timer->end('program2');
$timer->printTime('program2'); // 輸出:program2 run time 100.347042 ms
$timer->end();
$timer->printTime(); // 輸出:run time 264.035940 ms
program1 run time 163.285971 ms
program2 run time 100.347042 ms
run time 264.035940 ms
getTime() 回傳值存入陣列,請求結束時輸出 JSON 供前端圖表顯示。memory_get_peak_usage() 同時監測記憶體峰值。| 方案 | 精度 | 功能 | 適用場景 |
|---|---|---|---|
Timer 類別 | 微秒 | 多標記、手動控制 | 區塊級精準分析、API 除錯 |
| Xdebug Profiler | 微秒 | 完整呼叫堆疊、視覺化 | 深度效能分析、開發環境 |
| Tideways / Blackfire | 微秒 | 生產級採樣、火焰圖 | 線上持續監控 |
microtime() 直寫 | 微秒 | 簡單、無封裝 | 快速臨時測試 |
Timer 類別輕量零依賴,適合快速植入既有專案進行區塊級效能基準測試,是開發階段除錯與優化的得力小工具。