microtime() 返回當前 Unix 時間戳及微秒數。參數 true 時直接返回浮點數(秒.微秒),便於直接相減計算耗時。
<?php
// 頁面最頂部,盡可能早
$start_time = microtime(true);
?>
<!DOCTYPE html>
<html>
<head><title>頁面標題</title></head>
<body>
<!-- 頁面主要內容 -->
</body>
</html>
<?php
// 頁面最底部,輸出前
$end_time = microtime(true);
$execution_time = $end_time - $start_time;
printf('頁面執行時間:%.4f 秒', $execution_time);
?>
<?php
class Timer {
private $start;
private $checkpoints = [];
public function __construct() {
$this->start = microtime(true);
}
public function checkpoint($name) {
$this->checkpoints[$name] = microtime(true);
}
public function getElapsed($checkpoint = null) {
$end = $checkpoint ? $this->checkpoints[$checkpoint] : microtime(true);
return $end - $this->start;
}
public function report() {
$total = $this->getElapsed();
echo "總耗時:{$total}s\n";
foreach ($this->checkpoints as $name => $time) {
echo " {$name}: " . ($time - $this->start) . "s\n";
}
}
}
// 使用示例
$timer = new Timer();
// ... 業務邏輯 ...
$timer->checkpoint('DB查詢完成');
// ... 更多邏輯 ...
$timer->checkpoint('模板渲染完成');
$timer->report();
?>
<?php
$time = 0.123456;
echo sprintf('耗時:%.3f 秒', $time); // 0.123 秒
echo sprintf('耗時:%.2f 毫秒', $time*1000); // 123.46 毫秒
// 更直觀
echo number_format($time * 1000, 2) . ' ms';
?>