Timer class

sometimes it can be useful to time the execution of your code. I wanted recently to compare the performance of a single query compared to a procedural solution using three queries. The single query, beautifully formed by tsuji at tek-tips.com, took about 7 seconds to perform the necessary.

On the same dataset, the procedural code took about 0.7 seconds.

here is the code I use to time script execution

<?php
/**
 * class to handle script timing
 * 
 * usage
$timer = new timer();
$timer->start();
...code...
$timer->report();
 */
class timer{
	/**
	 * method to start the timer
	 * @return 
	 */
	public function start(){
		$this->start = microtime(true);
	}
 
	/**
	 * method to pause the timer
	 * @return 
	 */
	private function stop(){
		$this->stop = microtime(true);
	}
 
	/**
	 * method to stop the timer and report on the amount of time taken
	 * @return 
	 * @param object $format[optional]
	 */
	public function report(){
		$this->stop();
		$this->diff();
		printf ("<hr/>Script took %s seconds", number_format($this->diff, 8)); 
	}
 
	/**
	 * calculate the amount of time taken.
	 */
	private function diff(){
		$this->diff = $this->stop - $this->start;
	}
}
?>

Leave a comment

Your comment