As I expressed in the section that you just read, it’s possible to define yet another timer class using the advantages offered by PHP 5 with reference to its “microtime()” function. This brand new timing class can be created as follows: // define 'Timer' class with PHP 5 class Timer{ private $elapsedTime; // start timer public function start(){ if(!$this->elapsedTime=$this->getMicrotime()){ throw new Exception('Error obtaining start time!'); } } // stop timer public function stop(){ if(!$this->elapsedTime=round($this->getMicrotime()-$this->elapsedTime,5)){ throw new Exception('Error obtaining stop time!'); } return $this->elapsedTime; } //define private 'getMicrotime()' method private function getMicrotime(){ return microtime(); } } In this case, the above “Timer” class looks nearly identical to its PHP4-based counterpart. Aside from using exceptions to handle potential errors, the class in question uses a simple wrapper for the native “microtime()” function and it can be put to work as follows: try{ // 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'; } catch(Exception $e){ echo $e->getMessage(); exit(); } The previous example is very easy to grasp. Thus, it doesn’t merit any additional discussion here. However, feel free to tweak the source code of all the classes that I showed and add your own modifications to it. You’ll have a good time! To wrap up In this first article of the series, I introduced the basics on how to create benchmarking scripts with PHP 4 and PHP 5. This ranged from procedural approaches to object-oriented methods. You saw that there are different options for timing your applications. However, this journey isn’t finished yet, since in the next tutorial, I’ll show you how to use some of these classes to evaluate the performance of different PHP scripts. Don’t miss the next article!
blog comments powered by Disqus |
|
|
|
|
|
|
|