萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 精確測量腳本執行時間:microtime() 最佳實踐

使用 microtime() 精確統計 PHP 腳本耗時

在性能分析、接口耗時監控、慢查詢定位等場景,精確測量代碼執行時間至關重要。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 Profile 與生產級 APM

  • 開發環境:開啟 Xdebug xdebug.mode=profile,生成 cachegrind.out.*,用 QCacheGrind 或 PHPStorm 可視化分析調用鏈、耗時熱點。
  • 生產環境:接入 SkyWalking、Pinpoint、Datadog、Elastic APM 等無侵入式探針,自動採集請求鏈路、SQL 耗時、外部調用、異常堆棧。
  • 輕量級自建:中間件記錄請求耗時、內存峰值、慢 SQL 寫入 Kafka/ClickHouse,Grafana 儀表盤告警。

常見誤區

  1. time() 只能精確到秒,不可用於性能分析。
  2. 在循環中重複調用 microtime(true) 有一定開銷,高頻熱點路徑可用 hrtime(true) (PHP 7.3+,納秒級) 或擴展 hrtime。
  3. 不要在生產環境大量輸出調試信息,應寫入日誌或監控系統。
copyright © 萬盛學電腦網 all rights reserved