萬盛學電腦網

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

PHP 精確計算頁面執行時間:microtime_float() 函數封裝與應用

PHP 腳本執行時間測量:從微秒級計時到生產級性能監控

精確測量 PHP 代碼執行時間是性能優化、慢接口排查、SLA 監控的基礎。核心函數 microtime(true) 返回浮點數秒數(含微秒),配合簡單封裝即可滿足多數場景。

最簡核心代碼

<?php
// 頁面/腳本最頂部
$startTime = microtime(true);

// ... 業務邏輯代碼 ...

// 頁面/腳本最底部
$endTime = microtime(true);
$executionTime = $endTime - $startTime; // 秒,浮點數

// 格式化輸出
echo "頁面執行時間: " . number_format($executionTime, 4) . " 秒";
// 或毫秒
echo "頁面執行時間: " . round($executionTime * 1000, 2) . " 毫秒";
?>

封裝為可復用計時器函數/類

<?php
/**
 * 獲取當前微秒時間戳
 */
function microtimeFloat(): float
{
    return microtime(true);
}

/**
 * 簡單計時器:開始 -> 結束 -> 獲取耗時
 */
class SimpleTimer
{
    private float $start;
    private array $marks = [];

    public function __construct()
    {
        $this->start = microtime(true);
    }

    /** 標記一個節點 */
    public function mark(string $name): float
    {
        $now = microtime(true);
        $this->marks[$name] = $now - $this->start;
        return $this->marks[$name];
    }

    /** 獲取總耗時 */
    public function elapsed(): float
    {
        return microtime(true) - $this->start;
    }

    /** 生成報告 */
    public function report(int $precision = 4): string
    {
        $total = $this->elapsed();
        $lines = ["=== 計時器報告 ==="];
        $last = 0;
        foreach ($this->marks 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 SimpleTimer();
// ... 代碼段 1 ...
$timer->mark('數據庫查詢');
// ... 代碼段 2 ...
$timer->mark('模板渲染');
// ... 代碼段 3 ...
$timer->mark('響應發送');

error_log($timer->report());
// 輸出到錯誤日誌:
// === 計時器報告 ===
//   數據庫查詢          : 0.0452 秒 (+0.0452 秒)
//   模板渲染            : 0.0678 秒 (+0.0226 秒)
//   響應發送            : 0.0712 秒 (+0.0034 秒)
//   總計                : 0.0712 秒
?>

頁面級執行時間監控(自動佈局)

<?php
// bootstrap.php 或公共入口文件最早處
define('APP_START_TIME', microtime(true));
define('APP_START_MEM', memory_get_usage());
define('APP_START_PEAK_MEM', memory_get_peak_usage());

// 公共頁腳或 register_shutdown_function
function outputPagePerformance(): void
{
    // 僅開發/測試環境或采樣輸出
    if (!($_ENV['APP_DEBUG'] ?? false) && mt_rand(1, 100) > 10) return;

    $time = microtime(true) - APP_START_TIME;
    $memUsed = (memory_get_usage(true) - APP_START_MEM) / 1024 / 1024;
    $memPeak = (memory_get_peak_usage(true) - APP_START_PEAK_MEM) / 1024 / 1024;

    // 1. HTML 註釋輸出(前端不可见,開發者工具可見)
    echo "\n\n";

    // 2. 寫入日誌文件(生產環境推薦)
    $log = sprintf(
        "[%s] %s %s | Time: %.4fs | Mem: %.2fMB | Peak: %.2fMB | IP: %s\n",
        date('Y-m-d H:i:s'),
        $_SERVER['REQUEST_METHOD'] ?? 'CLI',
        $_SERVER['REQUEST_URI'] ?? '',
        $time, $memUsed, $memPeak,
        $_SERVER['REMOTE_ADDR'] ?? 'cli'
    );
    error_log($log, 3, __DIR__ . '/../logs/performance.log');

    // 3. 推送到監控系統
    // $prometheus->observe('php_request_duration_seconds', $time);
    // $statsd->timing('php.request.time', $time * 1000);
}
register_shutdown_function('outputPagePerformance');
?>

進階:Xdebug Profile 可視化分析

; php.ini / xdebug.ini
xdebug.mode=profile
xdebug.output_dir=/tmp/xdebug_profiles
xdebug.profiler_output_name=cachegrind.out.%p_%u

; 生成 cachegrind.out.* 文件,用 QCacheGrind (Windows/Linux) 或 KCacheGrind (Linux) 打開
; 可視化:調用鏈、每個函數自耗時/累計耗時、調用次數、內存分配

生產級 APM 方案對比

方案特點部署複雜度成本
SkyWalking (PHP 探針)全鏈路追蹤、拓撲圖、告警、開源中(需 Java 後端)免費
Pinpoint代碼級洞察、插件豐富、Java Agent高免費
Elastic APMELK 生態整合、機器學習異常檢測中免費/雲服務付費
Datadog / New Relic商業 SaaS、零配置、功能最全低較高
自建 ClickHouse + Vector/Logstash完全可控、成本低、需自行構建儀表盤高硬件成本

常見誤區與避坑

  1. ❌ 使用 time() 計算耗時 —— 精度只有 1 秒,毫無意義。
  2. ❌ 在循環中重複調用 microtime(true) 作為基準 —— 每次調用有開銷,應存入變量復用。
  3. ❌ 生產環境直接 echo 耗時 —— 干擾輸出、洩露信息,應寫入日誌或監控系統。
  4. ✅ 使用 hrtime(true) (PHP 7.3+) 獲取納秒級單調時鐘,避免系統時間調整影響。
  5. ✅ 區分「CPU 時間」與「牆鐘時間」:microtime 測量牆鐘時間(含 I/O 等待),CPU 密集型優化需關注 ru_utime+ru_stime (getrusage())。
copyright © 萬盛學電腦網 all rights reserved