Again?
Awhile ago I posted a PHP Execution class article for timing various PHP elements. Since then, a few developers have requested that I include the ability to start and start the timer, so you can be more precise with elements that you want to time and elements that you don’t. I decided to code this class in full PHP 5+ object-oriented structure. In addition to increased functionality, sticking to this style of programming supports PHP as an enterprise level language, and helps its standing among other more weathered and commercially used languages.
The Timer Script
This script returns the time in ms (milliseconds) rounded to the nearest ms when used in a php script or web page.
<?php class Timer{ private $start_time; private $end_time; private $accumulated_time; //Public constructor public function __construct() { $this->start_time = NULL; $this->end_time = NULL; $this->accumulated_time = 0; } //Public functions public function start() { if ($this->is_stopped()) { //add time so far to accumulated time //reset end time and set start time $this->accumulated_time += ($this->end_time - $this->start_time); $this->start_time = $this->get_timestamp(); $this->end_time = NULL; } else if (!$this->is_started()) { $this->start_time = $this->get_timestamp(); } } public function stop() { if ($this->is_started()) { $this->end_time = $this->get_timestamp(); } } public function reset() { $this->__construct(); } public function retrieve() { $this->stop(); return round($this->accumulated_time + ($this->end_time - $this->start_time)); } //Private functions private function is_started() { //if start is numeric but end is null, we are started if(is_numeric($this->start_time) && is_null($this->end_time)) { return true; } return false; } private function is_stopped() { //if end time is numeric, we have a stopped timer if(is_numeric($this->end_time)) { return true; } return false; } private function get_timestamp() { //retrieve seconds and microseconds (one millionth of a second) //multiply by 1000 to get milliseconds $timeofday = gettimeofday(); return 1000*($timeofday['sec'] + ($timeofday['usec'] / 1000000)); } } ?>
Usage
Using this script is relatively easy as you can probably see from the function names. The 4 main functions in addition to the constructor are start(), stop(), retrieve(), and reset(). Here is an example of usage of this class:
<?php //instantiate the timer object $timer = new Timer(); //start the timer $timer->start(); //... do something worth timing for($i=0;$i<10000000;$i++){} //stop the timer $timer->stop(); //... do something NOT worth timing //start the timer again $timer->start(); //... do something worth timing //stop the timer $timer->stop(); //print the time accumulated echo $timer->retrieve();


