分析函式效能、SQL 查詢耗時、API 回應延遲時,microtime(true) 提供微秒級精度,遠優於秒級 time()。封裝為類別可方便多點計時、巢狀計時與報表輸出。
<?php
declare(strict_types=1);
class HighPrecisionTimer
{
private float $startTime = 0.0;
private float $stopTime = 0.0;
private array $laps = [];
private string $label = '';
public function __construct(string $label = '')
{
$this->label = $label;
}
public function start(): self
{
$this->startTime = microtime(true);
return $this;
}
public function stop(): self
{
$this->stopTime = microtime(true);
return $this;
}
public function lap(string $name = ''): self
{
$now = microtime(true);
$this->laps[] = [
'name' => $name ?: 'lap_' . count($this->laps),
'time' => $now,
'duration' => $now - ($this->laps[-1]['time'] ?? $this->startTime),
];
return $this;
}
public function elapsed(): float
{
$end = $this->stopTime ?: microtime(true);
return $end - $this->startTime;
}
public function getLaps(): array
{
return $this->laps;
}
public function __toString(): string
{
$total = $this->elapsed();
$output = sprintf("[%s] 總耗時: %.6f 秒\n", $this->label ?: 'Timer', $total);
foreach ($this->laps as $lap) {
$output .= sprintf(" ├─ %s: %.6f 秒\n", $lap['name'], $lap['duration']);
}
return $output;
}
}
<?php
// 基本計時
$timer = new HighPrecisionTimer('API請求');
$timer->start();
// ... 業務邏輯 ...
usleep(150000); // 模擬 150ms 延遲
$timer->stop();
echo $timer; // 輸出格式化報表
// 多階段計時
$timer = new HighPrecisionTimer('訂單處理流程');
$timer->start();
$timer->lap('驗證參數');
validateInput();
$timer->lap('資料庫寫入');
saveToDb();
$timer->lap('發送通知');
sendNotification();
$timer->stop();
echo $timer;
/*
[訂單處理流程] 總耗時: 0.245123 秒
├─ 驗證參數: 0.012345 秒
├─ 資料庫寫入: 0.189012 秒
├─ 發送通知: 0.043766 秒
*/
// Laravel / Slim / 自製框架中介層範例
$app->add(function ($request, $handler) {
$timer = new HighPrecisionTimer('HTTP ' . $request->getMethod());
$timer->start();
$response = $handler->handle($request);
$timer->stop();
// 記錄慢請求
if ($timer->elapsed() > 1.0) {
error_log('Slow Request: ' . $timer);
}
$response->getHeaders()['X-Response-Time'] = $timer->elapsed();
return $response;
});