IMPORTANT PLEASE READ!
Website development and design blog, tutorials and inspiration

Timing PHP Script Execution

Timing PHP scripts is an easy way to monitor PHP script execution times and reduce page load times

By , Written on in PHP

Timing PHP Script Execution

279 words, estimated reading time 2 minutes.

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.
 
Website Performance Series
  1. Why Website Loading Times Are Vital - How to Improve Yours
  2. Improve Website Speed by Enabling Compression
  3. Timing PHP Script Execution

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.

  1. <?php
  2. $mtime = microtime();
  3. $mtime = explode(' ', $mtime);
  4. $mtime = $mtime[1] + $mtime[0];
  5. $starttime = $mtime;
  6. ?>

And this block goes at the end:

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

 

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.

  1.  
  2. function microtime_float()
  3. {
  4. list($usec, $sec) = explode(" ", microtime());
  5. return ((float)$usec + (float)$sec);
  6. }
  7.  
  8. function timing($timing)
  9. {
  10. if (count($timing) == 1)
  11. {
  12. echo '<p class="report_timing">Script execution '.$timing[0].' seconds<p></div>';
  13. }
  14. else
  15. {
  16. sort($timing);
  17. $ave = array_sum($timing)/count($timing);
  18. 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>';
  19. }
  20. }
  21.  

To use the functions:

  1.  
  2. $timing_loops = 10;
  3. for ($current_loop = 0; $current_loop < $timing_loops; $current_loop++)
  4. {
  5. $time_start = microtime_float();
  6. //.
  7. // Code to time here
  8. //.
  9. $timing[] = microtime_float() - $time_start;
  10. }
  11. timing($timing);
  12.  

Last updated on: Wednesday 21st June 2017

Did you Like this Post? Why not Like us on Facebook?

 

Comments
  1. Henrik
    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.