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

PHP Timer 類別:多標記程式碼執行時間精準監測

     編輯:PHP 相關知識

效能分析與除錯時,常需測量特定程式區塊的執行耗時。本文提供 Timer 類別,支援多標記獨立計時、微秒級精度、自動格式化輸出,適合插桿式效能分析。

類別功能

  • 多標記計時:可同時追蹤多個程式區塊(如資料庫查詢、API 呼叫、迴圈處理)。
  • 微秒精度:基於 microtime() 實現浮點數秒級測量。
  • 靈活 API:start()、end()、getTime()、printTime()。

核心程式碼

<?php
class Timer {
    private $_start = [];
    private $_end = [];
    private $_default_key = 'Timer';
    private $_prefix = 'Timer_';

    public function start($key = '') {
        $flag = $this->getKey($key);
        $this->_start[$flag] = $this->getMicrotime();
    }

    public function end($key = '') {
        $flag = $this->getKey($key);
        $this->_end[$flag] = $this->getMicrotime();
    }

    public function getTime($key = '') {
        $flag = $this->getKey($key);
        if (isset($this->_end[$flag]) && isset($this->_start[$flag])) {
            return (float)($this->_end[$flag] - $this->_start[$flag]);
        }
        return 0;
    }

    public function printTime($key = '') {
        $label = $key === '' ? $key : $key . ' ';
        printf("%srun time %f ms\n", $label, $this->getTime($key) * 1000);
    }

    private function getKey($key = '') {
        return $key === '' ? $this->_default_key : $this->_prefix . $key;
    }

    private function getMicrotime() {
        list($usec, $sec) = explode(' ', microtime());
        return (float)$usec + (float)$sec;
    }
}
?>

使用範例

<?php
require 'Timer.class.php';
$timer = new Timer();

$timer->start();           // 全域計時開始
$timer->start('program1'); // 區塊 1 計時
usleep(mt_rand(100000, 500000)); // 模擬耗時操作
$timer->end('program1');
$timer->printTime('program1'); // 輸出:program1 run time 163.285971 ms

$timer->start('program2');
usleep(mt_rand(100000, 500000));
$timer->end('program2');
$timer->printTime('program2'); // 輸出:program2 run time 100.347042 ms

$timer->end();
$timer->printTime(); // 輸出:run time 264.035940 ms

輸出結果

program1 run time 163.285971 ms
program2 run time 100.347042 ms
run time 264.035940 ms

進階應用建議

  • 自動收集報表:將 getTime() 回傳值存入陣列,請求結束時輸出 JSON 供前端圖表顯示。
  • 記憶體配合:搭配 memory_get_peak_usage() 同時監測記憶體峰值。
  • 中介軟體整合:在框架中間件中自動記錄路由處理時間、資料庫查詢數與耗時。
  • 生產環境採樣:僅對 1% 請求啟用詳細計時,避免效能影響。

替代方案比較

方案精度功能適用場景
Timer 類別微秒多標記、手動控制區塊級精準分析、API 除錯
Xdebug Profiler微秒完整呼叫堆疊、視覺化深度效能分析、開發環境
Tideways / Blackfire微秒生產級採樣、火焰圖線上持續監控
microtime() 直寫微秒簡單、無封裝快速臨時測試

Timer 類別輕量零依賴,適合快速植入既有專案進行區塊級效能基準測試,是開發階段除錯與優化的得力小工具。

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