//***************************************************************
//** title : A time measuring and performance benchmarking class.
//**
//** story : Sometimes you need to fine tune your php application
//** or just examine which parts of your code need more
//** time to be executed. This class will help you measure
//** execution times of any block of code you want.
//** You can even stick it in a loop to check whether its
//** iterations require even amounts of cpu time to be
//** executed, in order to spot possible anomalies in your
//** application's execution.
//**
//** author : Ioannis Cherouvim
//** e-mail : morales@hack.gr
//** date : 2005-06-21
//*******************************************************
class Perf {
var $init;
var $count;
var $temp;
//instantiate reader
function Perf() {
$this->init = $this->getmicrotime();
}
//start the clock
function start() {
$this->temp = $this->getmicrotime();
}
//stop the clock
function stop() {
$this->count[] = $this->getmicrotime() - $this->temp;
}
//show results, with a boolean parameter
function printResults($analytical) {
echo "Total execution time " . $this->getSize($this->getmicrotime() - $this->init)."<br/>";
$count = count($this->count);
if ($count==0) return;
$min=$this->count[0];
$max=$this->count[0];
$total=$mini=$maxi=0;
for($i=0; $i<$count; $i++) {
$value = $this->count[$i];
if ($value<$min) {$min = $value; $mini = $i;}
if ($value>$max) {$max = $value; $maxi = $i;}
$total+=$value;
if ($analytical) echo "•iteration #" . ($i+1) . " " . $this->getSize($this->count[$i])."<br/>";
}
echo "Total iterations " . $count . "<br/>";
echo "Average iteration time " . $this->getSize($total/$count)."<br/>";
echo "Min iteration time " . $this->getSize($min) . " on iteration #" . ($mini+1) . "<br/>";
echo "Max iteration time " . $this->getSize($max) . " on iteration #" . ($maxi+1) . "<br/>";
}
//private method to convert milliseconds into something more
//humanly readable
function getSize($size) {
$times = array("msecs", "secs", "mins", "hours", "days", "months", "years");
$divs = array(1000, 60, 60, 24, 30, 12);
$i = 0;
while ($i<count($divs) && $size >= $divs[$i]) {
$size/=$divs[$i];
$i++;
}
return round($size, 4)."Â ".$times[$i];
}
//private method to get the time
function getmicrotime(){
list($usec, $sec) = explode(" ",microtime());
return ((float)$usec + (float)$sec)*1000;
}
}
//****************************************************
//** An example use of this class
//****************************************************
$perf = new Perf();