Getting the Time a PHP Script Takes to Execute

July 20th, 2011 - Posted by Steve Marks to PHP, Web Development.

If your working with large resource intensive PHP scripts, or are simply looking to refine and optimize an existing bit of code, one of the steps you might take is to look at how long your PHP code is taking to run. We can do this within the PHP code itself by analyzing the time the script is kicked off and comparing it to the time the script completes.

I’ve included a simple example of this below:

// Place this at the very top of script
$start = microtime(TRUE);

// The body of script goes here with lots of wonderful code.

// Place this at the very bottom of script
$finish = microtime(TRUE);

// Subtract the start time from the end time to get our difference in seconds
$totaltime = $finish - $start;

echo "This script took ".$totaltime." seconds to run";

The code above uses the function microtime(). This returns the amount of time, including microseconds, since the unix epoch. By adding ‘TRUE’ as a parameter we get the number returned in seconds to the nearest microsecond.

Tags: ,
This entry was posted on Wednesday, July 20th, 2011 at 9:13 pm by +Steve Marks and is filed under PHP, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.

Fear not, we won't publish this

Comments (0)

No comments have been left yet. Be the first