<?php
$start = microtime(true); // 以 float 秒為單位
// 待測程式碼
$sum = 0;
for ($i = 0; $i < 100000; $i++) {
$sum += $i;
}
$end = microtime(true);
$elapsed = $end - $start;
echo "執行時間: $elapsed 秒"; // 例: 0.0045320987701416 秒
?>
function formatRuntime($seconds) {
if ($seconds < 1e-6) return round($seconds * 1e9, 2) . " ns";
if ($seconds < 1e-3) return round($seconds * 1e6, 2) . " µs";
if ($seconds < 1) return round($seconds * 1e3, 2) . " ms";
return round($seconds, 4) . " s";
}
echo "耗時: " . formatRuntime($elapsed);
針對大型專案建議使用專業分析工具:
// XHProf 範例
xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY);
// ... 執行程式碼 ...
$data = xhprof_disable();
// 儲存 $data 並用 xhprof_html 介面分析
microtime(true) 回傳 float,精度達微秒級hrtime(true) 取得奈秒級單調時鐘