Timing Your PHP Scripts

Posted by Nessa | Posted in , | Posted on April 15, 2007

0

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.

Share and Enjoy:
  • Digg
  • DZone
  • del.icio.us
  • Technorati
  • Facebook
  • Google Bookmarks
  • StumbleUpon
  • Twitter
  • Sphinn
  • Mixx
  • blogmarks
  • Furl
  • Reddit
  • Slashdot
  • RSS

Related posts:

  1. Command Line PHP: Part 3
  2. Command Line PHP: Part 2
  3. Simple MySQL Search Query
  4. Command Line PHP – Part 1
  5. Dun Dun Dunnnnnnnnn

Post a comment