microtime() 返回「微秒 秒」格式的字串,結合 explode() 即可得到浮點數時間戳,精度達微秒級。
<?php
// 程式最開頭
$pagestartime = microtime(true); // 直接取得 float,PHP 5.0+
?>
<!-- 網頁內容 -->
<?php
$pageendtime = microtime(true);
$totaltime = $pageendtime - $pagestartime;
printf('頁面執行時間:%.4f 秒', $totaltime);
?>
<?php
class Timer {
private $start;
public function __construct() { $this->start = microtime(true); }
public function elapsed($decimals = 4) {
return round(microtime(true) - $this->start, $decimals);
}
public function __toString() { return $this->elapsed() . ' 秒'; }
}
// 使用
$timer = new Timer();
// ... 業務邏輯 ...
echo '總耗時:' . $timer;
?>
關鍵點: PHP 5.0+ 直接傳 true 給 microtime() 即可取得 float,避免字串拆解的麻煩與精度損失。