在性能分析、接口耗時監控、慢查詢定位等場景,精確測量代碼執行時間至關重要。PHP 提供 microtime() 函數可獲取微秒級時間戳。
<?php
// 獲取當前時間戳(浮點數,秒.微秒)
$start = microtime(true);
// ... 你的業務代碼 ...
$end = microtime(true);
$elapsed = $end - $start; // 秒,浮點數
// 格式化輸出
printf("執行耗時: %.4f 秒 (%d 毫秒)", $elapsed, $elapsed * 1000);
?>
<?php
class Timer {
private float $start;
private array $laps = [];
private string $label;
public function __construct(string $label = 'default') {
$this->label = $label;
$this->start = microtime(true);
}
// 記錄分段時間
public function lap(string $name): float {
$now = microtime(true);
$elapsed = $now - $this->start;
$this->laps[$name] = $elapsed;
return $elapsed;
}
// 獲取總耗時
public function stop(): float {
return microtime(true) - $this->start;
}
// 格式化報告
public function report(int $precision = 4): string {
$total = $this->stop();
$lines = ["=== {$this->label} 計時報告 ==="];
$last = 0;
foreach ($this->laps as $name => $time) {
$lines[] = sprintf(" %-20s: %.*f 秒 (+%.*f 秒)", $name, $precision, $time, $precision, $time - $last);
$last = $time;
}
$lines[] = sprintf(" %-20s: %.*f 秒", '總計', $precision, $total);
return implode("\n", $lines);
}
}
// 使用示例
$timer = new Timer('訂單創建流程');
$orderId = createOrder($data);
$timer->lap('寫入主訂單');
deductStock($items);
$timer->lap('扣減庫存');
sendMqMessage('order.created', $orderId);
$timer->lap('發送消息');
sendSmsNotification($userPhone);
$timer->lap('發送短信');
error_log($timer->report());
// 輸出:
// === 訂單創建流程 計時報告 ===
// 寫入主訂單 : 0.0123 秒 (+0.0123 秒)
// 扣減庫存 : 0.0456 秒 (+0.0333 秒)
// 發送消息 : 0.0478 秒 (+0.0022 秒)
// 發送短信 : 0.1234 秒 (+0.0756 秒)
// 總計 : 0.1234 秒
?>
<?php
// 公共入口文件(如 index.php 或 bootstrap.php)
define('APP_START_TIME', microtime(true));
define('APP_START_MEM', memory_get_usage());
// 公共頁腳或終止處
function printPageStats() {
$time = microtime(true) - APP_START_TIME;
$mem = (memory_get_peak_usage(true) - APP_START_MEM) / 1024 / 1024;
// 僅開發環境輸出,或寫入監控系統
if (($_ENV['APP_DEBUG'] ?? false)) {
echo "";
}
}
register_shutdown_function('printPageStats');
?>
xdebug.mode=profile,生成 cachegrind.out.*,用 QCacheGrind 或 PHPStorm 可視化分析調用鏈、耗時熱點。time() 只能精確到秒,不可用於性能分析。microtime(true) 有一定開銷,高頻熱點路徑可用 hrtime(true) (PHP 7.3+,納秒級) 或擴展 hrtime。