Learning never exhausts the mind
Home >  Coding > PHP > Timing PHP Script Execution

Last Updated on by

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 
  $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);
One thought on “Timing PHP Script Execution
  • 23rd May 2014 at 12:00 am

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

    Reply

Leave a Reply

Fields marked with * are mandatory.

We respect your privacy, and will not make your email public. Hashed email address may be checked against Gravatar service to retrieve avatars. This site uses Akismet to reduce spam. Learn how your comment data is processed.