Tim TrottTim TrottDon't let your dreams just be dreams

Timing PHP Script Execution

By , Saturday 7th February 2009 in PHP

Another of my widely used PHP snippets is this timing function, which can be used to time a whole script execution, or a single function. This is especially important for optimizing script performance and reduction of page load times.

Again, this is one of those scripts I found on the net years ago and I have no idea where it came from.

This code goes at the top of the script or function you need to time.

<?php 
  $mtime = microtime(); 
  $mtime = explode(' ', $mtime); 
  $mtime = $mtime[1] + $mtime[0]; 
  $starttime = $mtime; 
?>

And this block goes at the end:

<?php
  $mtime = microtime(); 
  $mtime = explode(" ", $mtime);
  $mtime = $mtime[1] + $mtime[0]; 
  $endtime = $mtime; 
  $totaltime = ($endtime - $starttime); 
  echo '<!-- Script execution took ' .$totaltime. ' seconds -->';
?>

 

Using loops for average PHP script execution time

Measure PHP execution time using this small and simple script. This will allow you to run a specific set of php scripts or functions in a loop and generate an average execution time. This is very handy for performance tuning scripts.

 
function microtime_float() 
{
  list($usec, $sec) = explode(" ", microtime());
  return ((float)$usec + (float)$sec);
}
 
function timing($timing) 
{
  if (count($timing) == 1) 
  {
    echo '<p class="report_timing">Script execution '.$timing[0].' seconds<p></div>';
  }
  else 
  {
    sort($timing);
    $ave = array_sum($timing)/count($timing);
    echo '<p class="report_timing">Script execution over '.count($timing).' loops averages '.$ave.'seconds<br>Fastest: '.$timing[0].' seconds<br>Slowest: '.$timing[count($timing)-1].' seconds<p>/div>';
  }
}
 

To use the functions:

 
$timing_loops = 10;
for ($current_loop = 0; $current_loop < $timing_loops; $current_loop++) 
{
  $time_start = microtime_float();
  //.
  // Code to time here
  //.
  $timing[] = microtime_float() - $time_start;
}
timing($timing);
 

My website and its content are free to use without the clutter of adverts, tracking cookies, marketing messages or anything else like that. If you enjoyed reading this article, or it helped you in some way, all I ask in return is you leave a comment below or share this page with your friends. Thank you.

About the Author

Tim Trott

Tim is a professional software engineer, designer, photographer and astronomer from the United Kingdom. You can follow him on Twitter to get the latest updates.

Further Reading
One thought on “Timing PHP Script Execution”
  1. Gravatar
    Henrik

    FYI for those finding this: As of PHP 5.0.0, you can use microtime(true); to get a float value right away.

Leave a Reply

Your email address will not be published.