頁面執行時間監測是性能優化的基礎。本 Timer 類支持:
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,
];
// 發送到監控系統...
?>
fastcgi_finish_request() 後異步發送指標到 InfluxDB/Prometheus| 方案 | 精度 | 侵入性 | 適用場景 |
|---|---|---|---|
| 本 Timer 類 | 微秒 | 低(手動埋點) | 代碼級精細分析 |
| Xdebug Profiler | 微秒 | 零侵入 | 開發環境全鏈路分析 |
| XHProf / Tideways | 微秒 | 低(自動採樣) | 生產環境持續性能分析 |
| OpenTelemetry | 納秒 | 中(需埋點/SDK) | 分佈式鏈路追蹤 |
Timer 類以極簡代碼實現了核心計時需求,是輕量級項目、API 接口調試、局部性能優化的得力工具。