Web Design that taps into the haromny and vision of your dreams.

Timing PHP Script Execution

By on in Coding

279 words, estimated reading time 2 minutes.

Search Engine Optimisation Series
  1. SEO - Search Engine Optimization
  2. A Guide to the Robots.txt Exclusion Protocol
  3. What are XML sitemaps?
  4. Using Google Webmaster Tools
  5. Getting Started with Google Analytics
  6. Getting Started Earning Money with Adsense
  7. Why Website Loading Times Are Vital - How to Improve Yours
  8. Improve Website Speed by Enabling Compression
  9. Timing PHP Script Execution
  10. 8 Excellent (and Free!) Search Engine Optimization Websites

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.

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

And this block goes at the end:

  $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>';
    $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;

Last updated on: Wednesday 21st June 2017



Have a question or suggestion? Please leave a comment to start the discussion.



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

Reply to Henrik


Leave a Reply

Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

Your email address will not be published.