Timing PHP Script Execution To Improve PerformanceA short script for timing php script execution times which can be used for performance tuning or identifying bottlenecks in your scripts.
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.
<?php
$mtime = microtime();
$mtime = explode(' ', $mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;
?>
And this block goes at the end:
<?php
$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</div>';
}
else
{
sort($timing);
$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/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;
}
timing($timing);