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

PHP Timer 類:精準監測頁面執行時間

     編輯:PHP 綜合知識

功能特性

  • 支援多標記 (key) 獨立計時
  • 微秒級精度 (microtime)
  • 提供啟動、停止、獲取時長、格式化輸出介面

完整類別代碼

<?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 = '') {
        $flag = $this->_getKey($key);
        $label = $key === '' ? '' : $key . ' ';
        printf("%srun time %.4f 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
$timer = new Timer();

// 整體頁面計時
$timer->start();
// ... 業務邏輯 ...
$timer->end();
$timer->printTime(); // Timer run time 12.3456 ms

// 區塊計時
$timer->start('db_query');
// ... 資料庫查詢 ...
$timer->end('db_query');
$timer->printTime('db_query'); // Timer_db_query run time 5.6789 ms
?>

輕量、無依賴,適合性能分析與瓶頸定位。

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