首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 精確測量程式碼執行時間:microtime 實戰與最佳實踐

     編輯:PHP 相關知識

效能分析的第一步是精確測量。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
*/
?>

生產環境應用模式

1. 中介軟體記錄請求耗時

<?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;
    }
}
?>

2. SQL 查詢耗時監控

<?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;
}
?>

3. 函式級效能分析裝飾器

<?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;
});
?>

注意事項與陷阱

  • microtime(true) 回傳 float:PHP 7.1+ 精度足夠,舊版本可能有精度問題,嚴格場景可用 hrtime(true)(PHP 7.3+,納秒級整數)
  • 不要在迴圈內重複呼叫 microtime:系統呼叫有開銷,測量迴圈整體而非單次迭代
  • GC、Opcode 快取、JIT 預熱:首次執行較慢,基準測試需預熱後多次取平均
  • 生產環境採樣:全量測量有開銷,採用 1% 採樣率或僅記錄慢請求
  • 區分 Wall Time vs CPU Time:microtime 量牆鐘時間(含 I/O 等待),CPU 時間需用 ru_total 或 Xdebug/Blackfire

專業工具推薦

  • Xdebug + Webgrind/KCachegrind:函式級呼叫圖、耗時分佈
  • Blackfire.io:生產級零侵入分析、對比報告、CI/CD 整合
  • Tideways:輕量級 APM、支援 PHP 8.1+
  • Laravel Telescope / Clockwork:框架級請求、查詢、佇列、快取可視化

從 microtime(true) 開始,建立「測量 → 分析 → 優化 → 驗證」的效能改善閉環,是 PHP 開發者邁向高效能工程師的必修課。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved