函數實作
<?php
/**
* 取得程式執行時間(毫秒)
* @return float 執行時間,單位:毫秒
*/
function execute_time() {
// SYS_START_TIME 需在程式入口點定義:define('SYS_START_TIME', microtime(true));
$stime = explode(' ', SYS_START_TIME);
$etime = explode(' ', microtime());
return number_format(($etime[1] + $etime[0] - $stime[1] - $stime[0]), 6);
}
?>
使用方式
<?php
// 程式最開頭定義起始時間
define('SYS_START_TIME', microtime(true));
// ... 你的業務邏輯 ...
// 結束前呼叫
echo '執行時間:' . execute_time() . ' ms';
?>
替代寫法(PHP 5.4+ 更簡潔)
<?php
$start = microtime(true);
// ... 程式碼 ...
$end = microtime(true);
echo '執行時間:' . round(($end - $start) * 1000, 3) . ' ms';
?>
應用場景
- 效能瓶頸分析
- API 回應時間監控
- SQL 查詢耗時測量
- 演算法複雜度驗證