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

PHP 精確計算腳本執行時間的最佳實踐

     編輯:PHP 綜合知識

使用 microtime() 進行高精度計時

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,避免字串拆解的麻煩與精度損失。

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