php Timer 页面运行时间监测类
php Timer 页面运行时间监测类,可按不同key监测不同的运行时间。查看代码打印
01
<?php
02
/** Timer class, 计算页面运行时间,可按不同key计算不同的运行时间
03
* Date: 2014-02-28
04
* Author: fdipzone
05
* Ver: 1.0
06
*
07
* Func:
08
* publicstart 记录开始时间
09
* publicend 记录结束时间
10
* publicgetTime 计算运行时间
11
* pulbicprintTime 输出运行时间
12
* private getKey 获取key
13
* private getMicrotime 获取microtime
14
*/
15
16
class Timer{
17
18
private $_start = array();
19
private $_end = array();
20
private $_default_key = 'Timer';
21
private $_prefix = 'Timer_';
22
23
/** 记录开始时间
24
* @param String $key 标记
25
*/
26
public function start($key=''){
27
$flag = $this->getKey($key);
28
$this->_start[$flag] = $this->getMicrotime();
29
}
30
31
/** 记录结束时间
32
* @param String $key 标记
33
*/
34
public function end($key=''){
35
$flag = $this->getKey($key);
36
$this->_end[$flag] = $this->getMicrotime();
37
}
38
39
/** 计算运行时间
40
* @paramString $key 标记
41
* @return float
42
*/
43
public function getTime($key=''){
44
$flag = $this->getKey($key);
45
if(isset($this->_end[$flag]) && isset($this->_start[$flag])){
46
return (float)($this->_end[$flag] - $this->_start[$flag]);
47
}else{
48
return 0;
49
}
50
}
51
52
/** 输出页面运行时间
53
* @paramString $key 标记
54
* @return String
55
*/
56
public function printTime($key=''){
57
printf("%srun time %f ms\r\n", $key==''? $key : $key.' ', $this->getTime($key)*1000);
58
}
59
60
/** 获取key
61
* @paramString $key 标记
62
* @return String
63
*/
64
private function getKey($key=''){
65
if($key==''){
66
return $this->_default_key;
67
}else{
68
return $this->_prefix.$key;
69
}
70
}
71
72
/** 获取microtime
73
*/
74
private function getMicrotime(){
75
list($usec, $sec) = explode(' ', microtime());
76
return (float)$usec + (float)$sec;
77
}
78
79
}
使用示例:
查看代码打印
01
<?php
02
03
require 'Timer.class.php';
04
05
$timer = new Timer();
06
$timer->start();
$timer->start('program1');
$timer->end('program1');
$timer->printTime('program1');
$timer->start('program2');
usleep(mt_rand(100000,500000));
$timer->end('program2');
$timer->printTime('program2');
$timer->end();
$timer->printTime();
示例输出:
program1 run time 163.285971 ms
program2 run time 100.347042 ms
run time 264.035940 mswww.9ask.cn/suqian/
页:
[1]