Timing Your PHP Scripts
Posted by Nessa | Posted in code,php | Posted on April 15, 2007
1
This was just a little code addon that I put together as part of a tutorial I wrote on a friend’s site (and copied on mine) about PHP optimization. Added to a page on your site, it will calculate how much time it took for a page or script to execute using PHP’s microtime() function. I only added this to my main page, but you can easily create a plugin or include file to show the generation time of all your pages.
First, add this code to the very beginning of your PHP file:
<?php
$stime = microtime();
$sarray = explode(" ", $stime);
$stime = $sarray[1] + $sarray[0];
?>
Now, add this to the very end:
<?php
$etime = microtime();
$earray = explode(" ", $etime);
$etime = $earray[1] + $earray[0];
$ttime = $etime - $stime;
$ttime = round($ttime,3);
echo "This page loaded in $ttime seconds.";
?>
That was easy, wasn’t it? You should now see a little line at the bottom of your page that shows how long it took to execute. There is an example on the bottom of my home page.
No related posts.











You can do that in easier way by writing:
$t=microtime(true); //at top of your page execution
//and
echo “This page loaded in “.(microtime(true)-$t).” seconds.”; // at the end