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

PHP 精準計算代碼執行時間:Timer 類實現與微秒級優化

     編輯:PHP 相關知識

為什麼需要微秒級計時?

性能分析、瓶頸定位、基準測試都要求高精度計時。PHP microtime() 返回「微秒 秒」格式字符串,直接相減易丟失精度,封裝類可統一處理。

現代化 Timer 類(PHP 7.1+)

<?php
class Timer {
    private float $start = 0.0;
    private float $end = 0.0;

    public function start(): void {
        $this->start = microtime(true);
        $this->end = 0.0;
    }

    public function stop(): void {
        $this->end = microtime(true);
    }

    public function elapsed(): float {
        if ($this->end === 0.0) {
            $this->end = microtime(true);
        }
        return $this->end - $this->start;
    }

    public function elapsedMs(): float {
        return $this->elapsed() * 1000;
    }

    public function __toString(): string {
        return sprintf('%.6f ms', $this->elapsedMs());
    }
}

// 使用範例
$timer = new Timer();
$timer->start();

// 模擬耗時操作
usleep(150000); // 150 ms

$timer->stop();
echo "耗時: $timer\n"; // 輸出類似:耗時: 150.123456 ms

// 靜態快捷方法
echo Timer::measure(function() {
    usleep(50000);
}); // 輸出:50.001234 ms
?>

靜態測量輔助方法(可選擴展)

public static function measure(callable $fn): float {
    $t = new self();
    $t->start();
    $fn();
    $t->stop();
    return $t->elapsed();
}

避坑指南

  • 勿用 time():秒級精度,無法測量毫秒級操作。
  • 勿手動拆解 microtime() 字符串:直接用 microtime(true) 返回 float,簡潔且精確。
  • GC 干擾:長時間測試中垃圾回收可能引入波動,關鍵路徑可暫時 gc_disable()。
  • Xdebug/Blackfire 影響:開啟分析器時計時會顯著偏大,僅作相對對比參考。

生產級替代:專業分析工具

複雜應用建議使用:

  • Xdebug Profiler + kcachegrind/QCacheGrind 視覺化調用圖。
  • Blackfire.io:零侵入式持續性能分析,支援生產環境安全採樣。
  • Tideways:輕量級 APM,適合長期監控。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved