PHP: Measure How Long Your Script Runs

It’s often quite useful to know just how long a particular PHP script is taking to run, and of course, working this out and showing it on screen is a pretty simple thing to do.

Basically all you do is grab the time at the start of your script execution and then grab it right at the end again. Subtract the start from the finished and you’ll be left with the amount of time taken to execute.

We will use the handy PHP microtime function which returns the current Unix timestamp with microseconds to handle the time capture for us.

Note that this function is only available on operating systems that support the gettimeofday() system call.

So  now that I’ve explained to you how to do it, let us put it into action:

At the top of your script, enter:

$time_start = microtime(true);

Then at the bottom of your page, insert:

$time_end = microtime(true);
$time = $time_end - $time_start;
echo  round($time,2) . " s";

That’s it. You’re done! :)

About Craig Lotter

Craig Lotter is a 29-ish year old software and web developer by trade (currently working for Touchwork), who also just happens to never have been able to shake off that pesky inner child within. Call him a fanboy, geek, nerd or whatever you want, just so long as you enjoy what he writes. His main personal site can be found at http://www.craiglotter.co.za and his webcomic, House of C can be found at http://www.houseofc.codeunit.co.za/
This entry was posted in Technology & Code, Tutorials and tagged , , , , , . Bookmark the permalink.