If creating procedural timing scripts was a no-brainer process, then you’ll probably find that building a timer class is even simpler. Basically, constructing such a class depends on defining a couple of methods that behave as basic wrappers for the built-in PHP “microtime()” function. Considering the concepts deployed before, a typical timer class could be defined as follows: // define 'Timer' class with PHP 4 class Timer{ var $elapsedTime; // start timer function start(){ if(!$this->elapsedTime=$this->getMicrotime()){ trigger_error('Error obtaining start time!',E_USER_ERROR); } } // stop timer function stop(){ if(!$this->elapsedTime=round($this->getMicrotime()-$this->elapsedTime,5)){ trigger_error('Error obtaining stop time!',E_USER_ERROR); } return $this->elapsedTime; } //define private 'getMicrotime()' method function getMicrotime(){ list($useg,$seg)=explode(' ',microtime()); return ((float)$useg+(float)$seg); } } } As you can see, defining a timer class with PHP 4 is a very simple process. As I said before, all that I did here was create a wrapping method for the “microtime()” PHP native function, as well as define some additional methods that are useful for starting and stopping the corresponding timer. Of course, this is only an introductory example and can be greatly improved. However, if you need a basic but effective timer class and don't want to write complex code, you have one here that may fit your needs. All right, after showing you how to create a simple timer class with PHP 4, have a look at the following example, which demonstrates how to use it: // instantiate 'Timer' class $timer=&new Timer(); // start timer $timer->start(); // do nothing for a while usleep(100); // stop timer $elapsedTime=$timer->stop(); // display elapsed time echo 'Time spent in doing nothing was '.$elapsedTime.' seconds'; /* displays the following Time spent in doing nothing was 0.00996 seconds */ As shown above, the entire process for timing or benchmarking a particular script is reduced to calling up the respective “start()” and “stop()” methods that belong to the “Timer” class. That’s it. At this point, you hopefully have a clear idea of how to develop a timer class with PHP 4, since this is a no-brainer procedure that can be tackled even by beginners. Therefore, the next lesson of this tutorial will be focused on creating another handy timer class, this time using PHP 5. Want to learn how this will be done? Jump into the following section and keep reading.
blog comments powered by Disqus |
|
|
|
|
|
|
|