首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 程序執行時間測量:microtime() 精確計算頁面耗時

     編輯:PHP 相關知識

microtime() 高精度計時原理

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();
?>

常見誤區與優化建議

  • 不要用 date() 或 time():精度只有秒級,無法測量毫秒級性能
  • 避免在循環中重複調用 microtime():函數調用本身有開銷
  • 生產環境可用 XHProf / Blackfire / Tideways:專業分析器提供函數級、調用鏈級性能分析
  • CLI 腳本同樣適用:腳本開頭結尾埋點即可

輸出格式化技巧

<?php
$time = 0.123456;
echo sprintf('耗時:%.3f 秒', $time);        // 0.123 秒
echo sprintf('耗時:%.2f 毫秒', $time*1000); // 123.46 毫秒
// 更直觀
echo number_format($time * 1000, 2) . ' ms';
?>
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved