php实现的Timer页面运行时间监测类

2025-05-29 0 79

本文实例讲述了php实现的Timer页面运行时间监测类及其用法,是一款非常实用的PHP类文件。分享给大家供大家参考。具体分析如下:

php Timer页面运行时间监测类,可按不同key监测不同的运行时间

Timer.class.php类文件如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79
<?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

?>

demo示例代码如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21
<?php

require 'Timer.class.php';

$timer = new Timer();

$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运行输出:

?

1

2

3
program1 run time 163.285971 ms

program2 run time 100.347042 ms

run time 264.035940 ms

完整实例源码点击此处本站下载。

希望本文所述对大家的PHP程序设计有所帮助。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 php实现的Timer页面运行时间监测类 https://www.kuaiidc.com/103712.html

相关文章

发表评论
暂无评论