精准统计页面加载耗时,是性能优化、SLA 监控的基础。本文对比 time() 秒级与 microtime() 微秒级两种方案,给出生产可用的计时器封装类。
start = microtime(true);
}
public function lap($name = 'default') {
$now = microtime(true);
$this->laps[$name] = $now - $this->start;
return $this->laps[$name];
}
public function elapsed($name = null) {
if ($name) return $this->laps[$name] ?? null;
return microtime(true) - $this->start;
}
public function report() {
$total = $this->elapsed();
$out = sprintf("Total: %.4f s\n", $total);
foreach ($this->laps as $name => $t) {
$out .= sprintf(" %-20s %.4f s (%.1f%%)\n", $name, $t, $t/$total*100);
}
return $out;
}
}
// 使用示例
$timer = new Timer();
// ... DB 查询 ...
$timer->lap('db_query');
// ... 模板渲染 ...
$timer->lap('render');
// ... 发送响应 ...
echo $timer->report();
?>
index.php)最顶部实例化 $timer = new Timer();。lap('name')。report() 输出,绘制性能趋势图。xdebug.profiler 等调试扩展,避免干扰计时。微秒级计时 + 分段埋点,让性能瓶颈无处遁形。