萬盛學電腦網

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

PHP 函數執行時間測試類(效能分析工具)

自訂效能測試類 EfficiencyTester

封裝 microtime() 與 time(),支援微秒/秒模式、單次/多次平均測試,方便比較不同演算法或函數效能。

類別完整代碼

<?php
class EfficiencyTester {
    private $testTimes = 1000;

    private function getTime($model = 'MS') {
        return ($model === 'S') ? time() : microtime(true);
    }

    public function testOnce($func, $model = 'MS') {
        $start = $this->getTime($model);
        $func();
        $end = $this->getTime($model);
        return $end - $start;
    }

    public function test($func, $model = 'MS') {
        $total = 0;
        for ($i = 0; $i < $this->testTimes; $i++) {
            $total += $this->testOnce($func, $model);
        }
        return $total / $this->testTimes;
    }
}
?>

使用範例

require_once 'EfficiencyTester.class.php';
$tester = new EfficiencyTester();

// 測試內建函數
echo 'rand() 平均耗時: ' . $tester->test('rand') . ' 微秒';

// 測試自訂函數
$tester->test(function() {
    // 要測試的程式碼片段
    $a = md5('test');
});

設計考量

  • getTime() 統一取得時間戳,支援擴展其他時間來源
  • 預設 1000 次取平均,減少系統抖動影響
  • 傳入 callable 而非函數名字串,支援匿名函數與靜態方法
  • 注意:測試本身有額外開銷(迴圈、函數呼叫),結果僅供相對比較

進階建議

  1. 使用 hrtime(true)(PHP 7.3+)取得奈秒級單調時鐘,避免系統時間調整影響
  2. 整合 xhprof 或 Blackfire 進行生產級剖析
  3. 測試前預熱(執行幾次不計時)讓 JIT/OpCache 穩定
copyright © 萬盛學電腦網 all rights reserved