效能調優的第一步是測量。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 紀元起的浮點秒數,精度取決於系統硬體(通常可達微秒級)。hrtime(true) 取得奈秒級高解析度時間(相對時間),適合更精密的效能分析。掌握 microtime() 計時技巧,能幫助你快速定位效能瓶頸,優化關鍵演算法與資料庫查詢,是 PHP 開發者必備的基本功之一。