Location: PHPKode > scripts > CBenchmark > cbenchmark/clsBenchMark.php
<?php
/**
 * Function and code coverage benchmark class.
 * Calculates execution time of particular function and/or block of code.
 * 
 * @author Borislav Nedelchev
 * @package BenchTools
 * @version 1.0
 * @link snairl(at)yahoo(dot)com
 * @copyright 2006 (c) Borislav Nedelechev
 * 
 */
class CBenchmark{
	/**
	 * Results from bechmarking
	 * @access protected
	 *
	 * @var mixed
	 */
	var $tests;
	/**
	 * Total execution time of all code
	 * @access protected
	 *
	 * @var float
	 */
	var $total_time;
	/**
	 * Last label using with start method
	 * @access protected
	 *
	 * @var string
	 */
	var $last_label;

	function Benchmark(){
		$this->tests=array();
		$this->last_label=false;
	}

	/**
	 * @access private
	 * @return float
	 */
	function GetMicrotime()
	{
		list($usec, $sec) = explode(" ", microtime());
		return ((float)$usec + (float)$sec);
	}

	/**
	 * Benchmark execution of given function or class method
	 * @access public
	 *
	 * @param string $label
	 * @param mixed $func function or class method to be benchmarked
	 * @param mixed $params
	 */
	function do_benchmark($label,$func,$params=false){
		$start=$this->GetMicrotime();
		call_user_func_array($func,$params);
		$this->tests[$label]=$this->GetMicrotime()-$start;
	}

	/**
	 * @access private
	 * @param int $time
	 */
	function calcTotalTime($time){
		$this->total_time+=$time;
	}
	
	/**
	 * Display benchmark results
	 * @access public
	 *
	 */
	function ShowResults(){
		asort($this->tests);
		reset($this->tests);
		$this->total_time=0;
		array_walk($this->tests,array(&$this,'calcTotalTime'));
		printf("Total execution time:%.3fs\n",$this->total_time);
		while (list($label,$val)=each($this->tests)) {
			$percents=($val/$this->total_time)*100;
			printf("Function: [%'.-20s] Time:%.3fs (%04.1f%%)\n",$label,$val,$percents);
		}
		echo("Function compare:\n");
		$copy=$this->tests;
		while (list($label,$val)=each($this->tests)) {
			printf("%s:\n",$label);
			foreach ($copy as $comp_label=>$com_val){
				if($label==$comp_label)continue;
				$percents=(($com_val/$val)-1)*100;
				if($percents<0)$measure='slower';
				elseif($percents>0)$measure='faster';
				else $measure='equal ';
				printf("-[%'.20s] %' 10.1f%% - %s\n",$comp_label,abs($percents),$measure);
			}
		}
	}
	
	/**
	 * Start benchmark code coverage
	 *
	 * @access public
	 * @param string $label
	 */
	function Start($label){
		$this->tests[$label]=$this->GetMicrotime();
		$this->last_label=$label;
	}
	
	/**
	 * End of code coverage benchmark.
	 *
	 * @access public
	 * @param string $label if not provided last used label in Start function
	 * will be used
	 */
	function End($label=false){
		if($label===false)$label=$this->last_label;
		$this->tests[$label]=$this->GetMicrotime()-$this->tests[$label];
	}
}
?>
Return current item: CBenchmark