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

PHP 精確測量函數執行時間:microtime() 高精度計時技巧

     編輯:PHP 相關知識

PHP 精確測量函數執行時間:microtime() 高精度計時技巧

效能調優的第一步是測量。PHP 提供 microtime(true) 取得微秒級時間戳,透過記錄開始與結束時間差,即可精確計算程式碼區塊或函數的執行耗時。

基本計時模式

<?php
$longStr = 'this is a test to see how much time md5 function takes to execute over this string';

// 記錄開始時間(微秒浮點數)
$start = microtime(true);

// 要測試的程式碼
$md5 = md5($longStr);

// 計算耗時
$elapsed = microtime(true) - $start;

echo "執行耗時:$elapsed 秒\n";
// 輸出範例:執行耗時:7.1525573730469E-6 秒
?>

封裝為可重用計時器類

<?php
class Timer {
    private $start;
    private $end;

    public function start() {
        $this->start = microtime(true);
    }

    public function stop() {
        $this->end = microtime(true);
    }

    public function elapsed() {
        if ($this->start === null) return null;
        $end = $this->end ?? microtime(true);
        return $end - $this->start;
    }

    public function elapsedFormatted() {
        $elapsed = $this->elapsed();
        if ($elapsed === null) return '未開始計時';
        if ($elapsed < 0.001) return round($elapsed * 1_000_000, 2) . ' µs';
        if ($elapsed < 1) return round($elapsed * 1000, 2) . ' ms';
        return round($elapsed, 4) . ' s';
    }
}

// 使用範例
$timer = new Timer();
$timer->start();
// ... 執行某段程式碼 ...
$timer->stop();
echo '耗時:' . $timer->elapsedFormatted();
?>

進階:測量函數多次執行的平均耗時

<?php
function benchmark(callable $fn, int $iterations = 1000): float {
    $start = microtime(true);
    for ($i = 0; $i < $iterations; $i++) {
        $fn();
    }
    return (microtime(true) - $start) / $iterations;
}

$avg = benchmark(function() {
    md5('test string');
}, 10000);

echo "平均每次耗時:" . round($avg * 1_000_000, 3) . " 微秒";
?>

注意事項

  • microtime(true) 回傳自 Unix 紀元起的浮點秒數,精度取決於系統硬體(通常可達微秒級)。
  • 單次測量受系統負載影響大,建議多次執行取平均或中位數。
  • PHP 7.3+ 可使用 hrtime(true) 取得奈秒級高解析度時間(相對時間),適合更精密的效能分析。
  • 生產環境避免在關鍵路徑留下計時程式碼,或使用條件編譯/旗標控制。

總結

掌握 microtime() 計時技巧,能幫助你快速定位效能瓶頸,優化關鍵演算法與資料庫查詢,是 PHP 開發者必備的基本功之一。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved