性能分析、瓶頸定位、基準測試都要求高精度計時。PHP microtime() 返回「微秒 秒」格式字符串,直接相減易丟失精度,封裝類可統一處理。
<?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_disable()。複雜應用建議使用:
kcachegrind/QCacheGrind 視覺化調用圖。