php实现的Timer页面运行时间监测类
本文实例讲述了php实现的Timer页面运行时间监测类及其用法,是一款非常实用的PHP类文件。分享给大家供大家参考。具体分析如下:
该phpTimer页面运行时间监测类,可按不同key监测不同的运行时间。
Timer.class.php类文件如下:
<?php
/**Timerclass,计算页面运行时间,可按不同key计算不同的运行时间
*Date:2014-02-28
*Author:fdipzone
*Ver:1.0
*
*Func:
*publicstart记录开始时间
*publicend记录结束时间
*publicgetTime计算运行时间
*pulbicprintTime输出运行时间
*privategetKey获取key
*privategetMicrotime获取microtime
*/
classTimer{//classstart
private$_start=array();
private$_end=array();
private$_default_key='Timer';
private$_prefix='Timer_';
/**记录开始时间
*@paramString$key标记
*/
publicfunctionstart($key=''){
$flag=$this->getKey($key);
$this->_start[$flag]=$this->getMicrotime();
}
/**记录结束时间
*@paramString$key标记
*/
publicfunctionend($key=''){
$flag=$this->getKey($key);
$this->_end[$flag]=$this->getMicrotime();
}
/**计算运行时间
*@paramString$key标记
*@returnfloat
*/
publicfunctiongetTime($key=''){
$flag=$this->getKey($key);
if(isset($this->_end[$flag])&&isset($this->_start[$flag])){
return(float)($this->_end[$flag]-$this->_start[$flag]);
}else{
return0;
}
}
/**输出页面运行时间
*@paramString$key标记
*@returnString
*/
publicfunctionprintTime($key=''){
printf("%sruntime%fms\r\n",$key==''?$key:$key.'',$this->getTime($key)*1000);
}
/**获取key
*@paramString$key标记
*@returnString
*/
privatefunctiongetKey($key=''){
if($key==''){
return$this->_default_key;
}else{
return$this->_prefix.$key;
}
}
/**获取microtime
*/
privatefunctiongetMicrotime(){
list($usec,$sec)=explode('',microtime());
return(float)$usec+(float)$sec;
}
}//classend
?>
demo示例代码如下:
<?php
require'Timer.class.php';
$timer=newTimer();
$timer->start();
$timer->start('program1');
usleep(mt_rand(100000,500000));
$timer->end('program1');
$timer->printTime('program1');
$timer->start('program2');
usleep(mt_rand(100000,500000));
$timer->end('program2');
$timer->printTime('program2');
$timer->end();
$timer->printTime();
?>
demo运行输出:
program1runtime163.285971ms program2runtime100.347042ms runtime264.035940ms
完整实例源码点击此处本站下载。
希望本文所述对大家的PHP程序设计有所帮助。