Timer class
Posted: Tue Dec 18, 2007 6:03 pm
I wrote this simple timer class for a project I just finished. Hopefully others find it useful.
PHP5 only!
Usage
Page load times:
Benchmarking:
PHP5 only!
Code: Select all
<?PHP
/**********
* Class: Timer
* Purpose: Whatever you want - it's just a simple timer class
* Author: Dylan Anderson
* Date: December 18, 2007
* License: GPL
*/
class Timer
{
private $start;
private $end;
private $elapsed;
private $significant_digits = 2;
function __construct()
{
$this->start = microtime(true);
}
function resetStart()
{
$this->start = microtime(true);
}
function end()
{
$this->end = microtime(true);
}
function elapsed($significant_digits=FALSE)
{
$this->end();
$digits = ($significant_digits) ? $significant_digits : $this->significant_digits;
$this->elapsed = number_format($this->end - $this->start,$significant_digits);
return $this->elapsed;
}
function __get($name)
{
switch($name)
{
case 'start':
return $this->start;
case 'end':
return $this->end;
case 'elapsed':
return $this->elapsed();
}
}
}
?>Usage
Page load times:
Code: Select all
<?PHP
$Timer = new Timer();
//blah
//blah
//blah
echo "Page generated in ".$Timer->elapsed." seconds";
?>Benchmarking:
Code: Select all
<?PHP
$Timer = new Timer();
//For loop test
for($i = 0;$i<100;$i++)
{
$for_array[] = rand(1,100);
}
$for_time = $Timer->elapsed;
unset($for_array);
//While loop test
$counter = 0;
while($counter < 100)
{
$while_array[] = rand(1,100);
$counter++;
}
$while_time = $Timer->elapsed;
unset($while_array);
echo "For loop took $for_time seconds, while loop took $while_time seconds";
?>