在性能優化、接口響應監控、慢查詢定位等場景中,精確測量 PHP 腳本的執行耗時至關重要。PHP 提供 microtime() 函數可獲取微秒級時間戳,結合封裝類即可實現精準計時。
<?php
class Runtime {
private $startTime = 0;
private $stopTime = 0;
private function getMicrotime(): float {
[$usec, $sec] = explode(' ', microtime());
return (float)$usec + (float)$sec;
}
public function start(): void {
$this->startTime = $this->getMicrotime();
}
public function stop(): void {
$this->stopTime = $this->getMicrotime();
}
public function spent(): float {
return round(($this->stopTime - $this->startTime) * 1000, 1); // 毫秒
}
}
$runtime = new Runtime();
$runtime->start();
// 你的業務代碼
$a = 0;
for ($i = 0; $i < 1000000; $i++) {
$a += $i;
}
$runtime->stop();
echo "頁面執行時間: {$runtime->spent()} 毫秒";
microtime(true) 獲取浮點數時間戳,簡化代碼