萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 高精度計時器 Timer 類:多標籤性能分析與微秒級監測

一、設計目標

頁面執行時間監測是性能優化的基礎。本 Timer 類支持:

  • 多標籤並行計時(如:DB 查詢、API 調用、模板渲染)
  • 微秒級精度(基於 microtime(true))
  • 靈活的獲取與輸出方式

二、核心類實現

<?php
/**
 * Timer 類 - 頁面運行時間監測
 * 支持多標籤獨立計時
 */
class Timer {
    private $_start = [];
    private $_end = [];
    private $_default_key = 'Timer';
    private $_prefix = 'Timer_';

    /** 記錄開始時間
     * @param string $key 計時標籤,留空使用默認
     */
    public function start($key = '') {
        $flag = $this->getKey($key);
        $this->_start[$flag] = $this->getMicrotime();
    }

    /** 記錄結束時間
     * @param string $key 計時標籤
     */
    public function end($key = '') {
        $flag = $this->getKey($key);
        $this->_end[$flag] = $this->getMicrotime();
    }

    /** 獲取耗時(秒,浮點數)
     * @param string $key 計時標籤
     * @return float 耗時秒數,未完成返回 0
     */
    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;
    }

    /** 直接輸出耗時(毫秒)
     * @param string $key 計時標籤
     */
    public function printTime($key = '') {
        $label = $key === '' ? '' : $key . ' ';
        printf("%srun time %.3f ms\n", $label, $this->getTime($key) * 1000);
    }

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

    private function getMicrotime() {
        return microtime(true); // PHP 5.0+ 直接返回浮點數
    }
}
?>

三、使用示例

<?php
require 'Timer.class.php';

$timer = new Timer();

// 整頁計時
$timer->start();

// 模塊 1:數據庫查詢
$timer->start('db_query');
usleep(mt_rand(100000, 500000)); // 模擬查詢耗時
$timer->end('db_query');
$timer->printTime('db_query'); // 輸出: db_query run time 163.286 ms

// 模塊 2:外部 API 調用
$timer->start('api_call');
usleep(mt_rand(100000, 500000));
$timer->end('api_call');
$timer->printTime('api_call'); // 輸出: api_call run time 100.347 ms

// 結束整頁計時
$timer->end();
$timer->printTime(); // 輸出: run time 264.036 ms
?>

四、進階用法:嵌套計時與數據收集

<?php
$timer = new Timer();
$timer->start('total');

// 業務邏輯...
$timer->start('step1');
// ...
$timer->end('step1');

$timer->start('step2');
// ...
$timer->end('step2');

$timer->end('total');

// 獲取所有數據用於上報/日誌
$metrics = [
    'total_ms' => $timer->getTime('total') * 1000,
    'step1_ms' => $timer->getTime('step1') * 1000,
    'step2_ms' => $timer->getTime('step2') * 1000,
];
// 發送到監控系統...
?>

五、生產環境整合建議

  1. 自動化埋點:在框架基類 Controller/Service 中集成,自動記錄路由、DB、緩存、視圖耗時
  2. 非阻塞上報:使用 fastcgi_finish_request() 後異步發送指標到 InfluxDB/Prometheus
  3. 採樣控制:高流量下採用 1%~10% 採樣率,避免監控系統過載
  4. 分位數關注:關注 P50/P95/P99 而非平均值,發現長尾延遲

六、替代方案對比

方案精度侵入性適用場景
本 Timer 類微秒低(手動埋點)代碼級精細分析
Xdebug Profiler微秒零侵入開發環境全鏈路分析
XHProf / Tideways微秒低(自動採樣)生產環境持續性能分析
OpenTelemetry納秒中(需埋點/SDK)分佈式鏈路追蹤

Timer 類以極簡代碼實現了核心計時需求,是輕量級項目、API 接口調試、局部性能優化的得力工具。

copyright © 萬盛學電腦網 all rights reserved