Get Accurate Script Execution Time in PHP

This small code can be quite helpful if you need to find out what is taking so long to load in your script(s).
It will determine the time taken for your PHP script(s) to execute, accurate to 0.000000000000001 seconds.

The Code

// put this at the top of your page/script
$exectime = microtime();
$exectime = explode(" ",$exectime);
$exectime = $exectime[1] + $exectime[0];
$starttime = $exectime;

/*
 *   place your script(s) to here
 */


// put this at the bottom of your page/script
$exectime = microtime();
$exectime = explode(" ",$exectime);
$exectime = $exectime[1] + $exectime[0];
$endtime = $exectime;
$totaltime = ($endtime - $starttime);
echo "This page was created in ".$totaltime." seconds";

…and that’s all! Happy debugging!

Join the Conversation

10 Comments

  1. Hi, nice script, but can you tell me in witch file to place this for a wordpress website? I have a slow time (3 seconds) if I place this in the index.php file in the middle I placed this code, alredy there. Is this correct?

    1. You have to put the entry point (lines 2-5) into your header.php file as first element and the stopper (lines 12-16/17) into your footer.php as last element. This way you get the most accurate values.
      index.php is not the correct place, since script execution starts earlier and you will not get accurate results.

  2. Ok, so I’ve tried this method as well as others in a WordPress theme (using header.php and footer.php) and yet I always get some gargantuan number rather than the actual time it took the page to load…

    I put the start timer as the first item in header.php and the stop timer as the last thing in footer.php (set to echo an html comment) and here’s the results I’m getting:

    </body>
    </html>
    <!– page rendered in 1321818086.6252 seconds –>

    1. Either your script is taking a ridiculous time to load or there is some error in your code. ;)
      I suggest you to do some debugging between the lines (check for where you are getting lost $exectime/$starttime).

    2. Josh, the variable from header.php is not visible in footer.php, that’s why you got so much time…
      the most correct way of getting the execution time is to put it in index.php

      $start_time = microtime(true);
      /** Loads the WordPress Environment and Template */
      require('./wp-blog-header.php');
      echo "<!-- Executed in " . (microtime(true) - $start_time) . " seconds -->";

      Added code tags :) ~admin

      1. Thanks for your input Slava!
        Another way would be to just introduce the needed variables in your functions file and use it in header and footer as in the example above.

  3. This script is provided as is. Although tested and found as error-free, no responsibility is taken for any misuse of the script, or damage caused by using it.

Leave a comment

Your email address will not be published. Required fields are marked *