封裝 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() 統一取得時間戳,支援擴展其他時間來源callable 而非函數名字串,支援匿名函數與靜態方法hrtime(true)(PHP 7.3+)取得奈秒級單調時鐘,避免系統時間調整影響xhprof 或 Blackfire 進行生產級剖析