PHP Script Timer

Timer class defenition

This a simple PHP class to test the speed of my scripts, it can be embedded into any PHP script to measure the execution time of a selected piece of code. It is deliberately very simple to prevent any significant increase in execution time.

Class Definition <?php
class timer
{
    private 
$start_time;
    private 
$end_time;

    public function 
start()
    {
        
$this->start_time microtime(true);
    }

    public function 
stop()
    {
        
$this->end_time microtime(true);
    }

    public function 
get_result()
    {
        
$result $this->end_time $this->start_time;
        return 
round($result3); // result in seconds, rounded to 3 decmal places
    
}
}
?>

 

Using the timer

Using the class is very simple, as it only has three very small functions.

  1. Create an instance of timer
  2. At the beginning of your script, call the start() function.
  3. now the time is running, the code you want to measure comes next.
  4. At the end of your script, call the stop() function
  5. The running time is now stared in the timer object, you can call get_result() at any time to find out the time logged.
Example <?php
$timer 
= new timer();
$timer->start();


for(
$x=0;$x<20;$x++)
{
    
password_hash("secret_password"PASSWORD_DEFAULT);
}


$timer->stop();

echo 
"<p>" $timer->get_result() . " seconds to generate 20 password hashes</p>";
?>