PHP 页面运行时间监测类 Timer 的实现与使用
介绍一个用于计算页面及各功能模块运行时间的 PHP Timer 类。该工具类支持为不同代码块设置独立的标识符(key)进行并行计时,输出精确到毫秒的执行时长,是分析 PHP 脚本性能、定位局部卡顿问题的实用组件。
TIMER 类的核心功能
Timer 类的设计目的是提供细粒度的时间监控能力。相比仅记录整个脚本总运行时间的简单方案,它允许开发者标记具体的业务逻辑或关键操作,从而对比不同阶段的耗时差异。该类主要包含以下核心方法:
start($key):记录指定标记的开始时间,若无参数则默认为全局开始点。end($key):记录指定标记的结束时间,同样支持默认标记。getTime($key):计算指定标记从 start 到 end 的时间差,单位为秒(浮点数)。printTime($key):直接格式化输出指定标记的运行时间(毫秒),便于调试日志查看。
类文件完整源码
以下是 Timer.class.php 的完整实现。该类利用 microtime() 获取高精度时间戳,通过内部数组分别存储每个标记的起止时间。
<?php
/** Timer class, 计算页面运行时间,可按不同key计算不同的运行时间
* Date: 2014-02-28
* Author: fdipzone
* Ver: 1.0
*
* Func:
* public start 记录开始时间
* public end 记录结束时间
* public getTime 计算运行时间
* pulbic printTime 输出运行时间
* private getKey 获取key
* private getMicrotime 获取microtime
*/
class Timer{ // class start
private $_start = array();
private $_end = array();
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
*/
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]);
}else{
return 0;
}
}
/** 输出页面运行时间
* @param String $key 标记
* @return String
*/
public function printTime($key='') {
printf("%srun time %f ms\r\n", $key==''? $key : $key.' ', $this->getTime($key)*1000);
}
/** 获取key
* @param String $key 标记
* @return String
*/
private function getKey($key='') {
if($key=='') {
return $this->_default_key;
}else{
return $this->_prefix.$key;
}
}
/** 获取microtime
*/
private function getMicrotime(){
list($usec, $sec) = explode(' ', microtime());
return (float)$usec + (float)$sec;
}
} // class end
?免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









