This article describes the PHP implementation of timer page running time monitoring class and its usage, is a very practical PHP class file. Share to everyone for your reference. The specific analysis is as follows:
The PHP timer page runs the time monitoring class, can monitor different running time according to different key.
The Timer.class.php class files are as follows:
<?php
/** Timer class, calculates the page run time, can calculate different running time according to different key
* date:2014-02-28
* Author:fdipzone
* ver:1.0
*
* Func:
* Public start record Starting time
* Public ending record end time
* Public GetTime calculation run time
* Pulbic Printtime Output run time
* Private Getkey Get key
* Private Getmicrotime Get Microtime
*/
Class timer{//Class start
Private $_start = Array ();
Private $_end = Array ();
Private $_default_key = ' Timer ';
Private $_prefix = ' timer_ ';
/** Record start time
* @param String $key Tag
*/
Public Function Start ($key = ') {
$flag = $this->getkey ($key);
$this->_start[$flag] = $this->getmicrotime ();
}
/** Record End time
* @param String $key Tag
*/
Public Function End ($key = ' ") {
$flag = $this->getkey ($key);
$this->_end[$flag] = $this->getmicrotime ();
}
/** Calculation Run time
* @param String $key Tag
* @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;
}
}
/** Output page Run time
* @param String $key Tag
* @return String
*/
Public Function printtime ($key = ' ") {
printf ("%srun time%f msrn", $key = = '? $key: $key. ' ', $this->gettime ($key) *1000);
}
/** Get key
* @param String $key Tag
* @return String
*/
Private Function Getkey ($key = ' ") {
if ($key = = ") {
return $this->_default_key;
}else{
Return $this->_prefix. $key;
}
}
/** Get Microtime
*/
Private Function Getmicrotime () {
List ($usec, $sec) = Explode (', microtime ());
return (float) $usec + (float) $sec;
}
}//Class end
?>
Demo sample code is as follows:
<?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 Run output:
Program1 Run time 163.285971 ms
Program2 Run time 100.347042 ms
Run time 264.035940 ms
I hope this article will help you with your PHP program design.