Date & Time
|
|
|
|
<?php static $timerGap = 0;
// Merge both parts of a microtime() result into a float.
// microtime() function returns a string like "0.324324 332144"
// The first part is the milliseconds
// The second part is the seconds elapsed from Jan 1st of 1970 function getmicrotime($mt) {
list($a, $b) = explode(" ", $mt);
return ((float)$a + (float)$b);
}
// Evaluate the time needed to retrieve start & stop timers.
// Gap is the time needed to get start then stop time
// Due to memory allocations involved in instance creation
// of the object, evaluating the time slice needed for
// timer initialization and destroy give more accurate results. function initGap() {
global $timerGap;
$timerGap = "GAPTEST"; //eqv 0 but not 0
$vmax = 0;
$vmin = 1;
for ($i=0;$i<10;$i++) {
$subtest = NULL; //unalloc memory space
$subtest = new timer();
$subtest->result();
$v = $subtest->result();
if ($v>$vmax) $vmax=$v;
if ($v<$vmin) $vmin=$v;
}
$timerGap = $vmin;
}
class timer {
var $tmStart = 0; // Start timestamp, microtime format
var $tmStop = 0; // Stop timestamp, microtime format
var $tmCount = 1; // Number of cycles in user's test loop
var $tmGap = 0; // Gap used (taken from the result)
// Initializes and start the timer
// Call initGap if it hasn't been done before
function timer($counter=1) {
global $timerGap;
if ($timerGap===0) initGap();
$this->tmGap = $timerGap;
$this->tmCount = (int)($counter<=0?1:$counter);
$this->tmStart = microtime();
}
// Reset the start timer
// Reevaluate Gap Time considering static calls
function reset($counter=1) {
$this->tmStop = 0;
$this->tmCount = 1;
$this->tmStart = microtime();
$this->tmGap = $this->result(); //more accurate gap
$this->tmStop = 0;
$this->tmCount = (int)($counter<=0?1:$counter);
$this->tmStart = microtime();
}
// Stops the timer and returns elapsed time
// Multiple calls to the result
function result() {
$mt = microtime();
if ($this->tmStop===0) $this->tmStop = $mt;
$tm1 = getmicrotime($this->tmStop);
$tm2 = getmicrotime($this->tmStart);
return ($tm1-$tm2-$this->tmGap)/$this->tmCount;
}
} ?>
|
|
|
Usage Example
|
Example A:
$tick = new timer();
echo "this is a test<br>";
$z = $tick->result();
echo "writing the previous line has taken ".$tick->result()." seconds";
assert $z==$tick->result();
Example B:
$tick = new timer(50);
for ($i=0;$i<50;$i++) {
$qry = mysql_query("SELECT COUNT(*) FROM table") or die(mysql_error());
$count = mysql_result($qry,0);
}
$elapsed = $tick->result();
echo "Each iteration of the loop takes $elapsed seconds";
Example C:
$tick = new timer();
# Your initialization code..
foreach ($libs as $lib) {
$tick->reset();
register_library($lib); #or any function to test..
$vtot += $values[$i++] = $tick->result();
}
echo "$i tests passed for a total time of $vtot";
|
|
|
Rate This Script
|
|
|
|