Timing PHP Script Execution To Improve Performance

A short script for timing php script execution times which can be used for performance tuning or identifying bottlenecks in your scripts.

By Tim Trott | PHP Tutorials | February 7, 2009

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 optimising 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
<?php 
  $mtime = microtime(); 
  $mtime = explode(' ', $mtime); 
  $mtime = $mtime[1] + $mtime[0]; 
  $starttime = $mtime; 
?>

And this block goes at the end:

php
<?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.

php
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</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/div>';
  }
}

To use the functions:

php
$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);
Was this article helpful to you?
 

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

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.

This post has 1 comment(s). Why not join the discussion!

We respect your privacy, and will not make your email public. Learn how your comment data is processed.

  1. HE

    On Friday 23rd of May 2014, Henrik said

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