摘要:本文主要向大家介绍了PHP语言 Timer 页面运行时间监测类,通过具体的实例向大家展示,希望对大家学习php语言有所帮助。
本文主要向大家介绍了PHP语言 Timer 页面运行时间监测类,通过具体的实例向大家展示,希望对大家学习php语言有所帮助。
php Timer 页面运行时间监测类,可按不同key监测不同的运行时间
Timer.class.php
[php] view plain copy
1. <?php
2. /** Timer class, 计算页面运行时间,可按不同key计算不同的运行时间
3. * Date: 2014-02-28
4. * Author: fdipzone
5. * Ver: 1.0
6. *
7. * Func:
8. * public start 记录开始时间
9. * public end 记录结束时间
10. * public getTime 计算运行时间
11. * pulbic printTime 输出运行时间
12. * private getKey 获取key
13. * private getMicrotime 获取microtime
14. */
15.
16. class Timer{ // class start
17.
18. private $_start = array();
19. private $_end = array();
20. private $_default_key = 'Timer';
21. private $_prefix = 'Timer_';
22.
23.
24. /** 记录开始时间
25. * @param String $key 标记
26. */
27. public function start($key=''){
28. $flag = $this->getKey($key);
29. $this->_start[$flag] = $this->getMicrotime();
30. }
31.
32.
33. /** 记录结束时间
34. * @param String $key 标记
35. */
36. public function end($key=''){
37. $flag = $this->getKey($key);
38. $this->_end[$flag] = $this->getMicrotime();
39. }
40.
41.
42. /** 计算运行时间
43. * @param String $key 标记
44. * @return float
45. */
46. public function getTime($key=''){
47. $flag = $this->getKey($key);
48. if(isset($this->_end[$flag]) && isset($this->_start[$flag])){
49. return (float)($this->_end[$flag] - $this->_start[$flag]);
50. }else{
51. return 0;
52. }
53. }
54.
55.
56. /** 输出页面运行时间
57. * @param String $key 标记
58. * @return String
59. */
60. public function printTime($key=''){
61. printf("%srun time %f ms\r\n", $key==''? $key : $key.' ', $this->getTime($key)*1000);
62. }
63.
64.
65. /** 获取key
66. * @param String $key 标记
67. * @return String
68. */
69. private function getKey($key=''){
70. if($key==''){
71. return $this->_default_key;
72. }else{
73. return $this->_prefix.$key;
74. }
75. }
76.
77.
78. /** 获取microtime
79. */
80. private function getMicrotime(){
81. list($usec, $sec) = explode(' ', microtime());
82. return (float)$usec + (float)$sec;
83. }
84.
85.
86. } // class end
87.
88. ?>
demo:
[php] view plain copy
1. <?php
2.
3. require 'Timer.class.php';
4.
5. $timer = new Timer();
6. $timer->start();
7.
8. $timer->start('program1');
9. usleep(mt_rand(100000,500000));
10. $timer->end('program1');
11. $timer->printTime('program1');
12.
13. $timer->start('program2');
14. usleep(mt_rand(100000,500000));
15. $timer->end('program2');
16. $timer->printTime('program2');
17.
18. $timer->end();
19. $timer->printTime();
20.
21. ?>
demo运行输出:
[plain] view plain copy
1. program1 run time 163.285971 ms
2. program2 run time 100.347042 ms
3. run time 264.035940 ms
本文由职坐标整理并发布,了解更多内容,请关注职坐标编程语言PHP频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号