php Timer 頁面運行時間監測類,可按不同key監測不同的運行時間
Timer.class.php
<?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
?>
查看本欄目