效能分析的第一步是精確測量。PHP 提供 microtime() 取得微秒級時間戳,配合簡單運算即可獲得程式碼區塊執行耗時。本文介紹核心用法、封裝技巧與生產環境應用模式。
<?php $t1 = microtime(true); // 取得浮點數秒數(含微秒) // ... 待測量的程式碼 ... echo "Hello World!"; $t2 = microtime(true); echo '耗時: ' . round($t2 - $t1, 3) . ' 秒'; // 保留 3 位小數(毫秒級) ?>
<?php
$start_time = microtime(true); // 程式開始時間
echo "Hello World!<br />"; // 你的業務代碼
$end_time = microtime(true); // 程式結束時間
$total = $end_time - $start_time; // 計算差值
echo "此 PHP 檔案程式碼執行了 {$total} 秒";
?>
<?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): void {
$total = $this->stop();
echo "[{$this->label}] Total: " . round($total, $precision) . "s\n";
foreach ($this->laps as $name => $time) {
echo " └─ {$name}: " . round($time, $precision) . "s\n";
}
}
}
// 使用範例
$timer = new Timer('User Registration');
$user = createUser($data);
$timer->lap('create_user');
$wallet = createWallet($user->id);
$timer->lap('create_wallet');
sendWelcomeEmail($user->email);
$timer->lap('send_email');
$timer->report();
/*
[User Registration] Total: 0.2451s
└─ create_user: 0.0823s
└─ create_wallet: 0.0412s
└─ send_email: 0.1216s
*/
?>
<?php
// Laravel 中介軟體範例
class LogRequestDuration {
public function handle($request, Closure $next) {
$start = microtime(true);
$response = $next($request);
$duration = microtime(true) - $start;
// 記錄慢請求(> 1 秒)
if ($duration > 1.0) {
Log::warning('Slow request', [
'url' => $request->fullUrl(),
'method' => $request->method(),
'duration_ms' => round($duration * 1000, 2),
'user_id' => $request->user()?->id,
'ip' => $request->ip(),
]);
}
// 回應標頭帶上耗時(前端效能分析用)
$response->headers->set('X-Response-Time', round($duration * 1000, 2) . 'ms');
return $response;
}
}
?>
<?php
// PDO 封裝範例
function queryWithTiming(PDO $pdo, string $sql, array $params = []): array {
$start = microtime(true);
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$duration = microtime(true) - $start;
if ($duration > 0.5) { // 慢查詢閾值 500ms
error_log(sprintf(
"[SLOW SQL] %.3fs | %s | params: %s",
$duration, $sql, json_encode($params)
));
}
return $result;
}
?>
<?php
function profile(callable $fn): callable {
return function(...$args) use ($fn) {
$start = microtime(true);
$result = $fn(...$args);
$duration = microtime(true) - $start;
// 可接入 StatsD、Prometheus、日誌系統
metrics()->timing('php.function.' . (new ReflectionFunction($fn))->getShortName(), $duration * 1000);
return $result;
};
}
// 使用
$heavyComputation = profile(function($n) {
// 複雜計算...
return $result;
});
?>
hrtime(true)(PHP 7.3+,納秒級整數)microtime 量牆鐘時間(含 I/O 等待),CPU 時間需用 ru_total 或 Xdebug/Blackfire從 microtime(true) 開始,建立「測量 → 分析 → 優化 → 驗證」的效能改善閉環,是 PHP 開發者邁向高效能工程師的必修課。