microtime() 返回當前 Unix 時間戳含微秒部分。關鍵參數 true 讓其返回 float 類型 而非字串,直接可進行數學運算。
<?php
$t1 = microtime(true); // 開始時間(浮點秒)
// ... 待測代碼區塊 ...
// 例:資料庫查詢、複雜計算、API 請求等
$t2 = microtime(true); // 結束時間
$elapsed = round($t2 - $t1, 3); // 保留 3 位小數(毫秒級)
echo "耗時: {$elapsed} 秒";
// 輸出示例: 耗時: 0.042 秒
?>
0.0419999999 等長尾class Timer {
private $start;
private $laps = [];
public function start() {
$this->start = microtime(true);
return $this;
}
public function lap($label = '') {
$now = microtime(true);
$this->laps[] = ['label' => $label, 'time' => $now - $this->start];
$this->start = $now; // 重置起點,支援分段計時
return $this;
}
public function stop() {
$total = microtime(true) - $this->start;
$this->laps[] = ['label' => 'TOTAL', 'time' => $total];
return $this;
}
public function report($precision = 4) {
foreach ($this->laps as $lap) {
printf("%-20s: %.*f 秒\n", $lap['label'], $precision, $lap['time']);
}
}
}
// 使用示例
$timer = new Timer();
$timer->start()
->lap('DB 連接')
->lap('查詢執行')
->lap('數據轉換')
->stop()
->report(4);
| 誤區 | 正確做法 |
|---|---|
用 time() 計時 | 精度只到秒,無法測量毫秒級操作 |
用 date('u') 取微秒 | 僅返回微秒部分,跨秒邊界會出錯 |
| 單次測試得出結論 | 需多次運行取中位數,排除 GC、快取干擾 |
| 忽略 Opcode 快取預熱 | 首次請求含編譯開銷,應預熱後再測 |
hrtime() (7.3+):納秒級單調時鐘,免受系統時間調整影響microtime(true) 是 PHP 最輕量、無依賴的微秒級計時工具。掌握 float 運算 + round 取精 + 封裝復用 三步法,能覆蓋 90% 的性能排查場景。複雜系統請升級專業 Profiler——工具解放雙手,原理指引方向。