Calculating the execution time of PHP scripts

While working on the problems from Project Euler, my scripts were required to perform all the calculations under 1 minute, so I decided to look around for some snippets that would help me achieve just that.

I found exactly what I wanted in two locations.

First, in SNIPPLR‘s library of scripts, I found one elegant and quite short script, posted by ibomb on the 29th of April, 2008.

Adequately called “Calculating script execution time“, it is displayed below:

<?php
$start = (float) array_sum(explode(' ',microtime()));
// put here the code that you want to render
$end = (float) array_sum(explode(' ',microtime()));
echo "Processing time: ". sprintf("%.4f", ($end-$start))." seconds";
?>

The second I found at DeveloperFusion, published by Gringod on the 8th of March, 2002. The original code was posted by Lio on ASP, so I’m told, by I couldn’t track it down. The script called “Determine execution time in PHP“, can be found below:

// put this at the top of the page
<?php
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;
?>
 
// put other code and html in here
 
// put this code at the bottom of the page
<?php
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = ($endtime - $starttime);
echo "This page was created in ".$totaltime." seconds";
?>

Personally, I like the first one better, for reasons of elegance alone, but I’ve thoroughly tested the second one as well, and I couldn’t find it failing in any way. I’ve no doubt that it can be improved further, given that it was written 9 years ago, so I welcome whoever’s up for the job to do it.

Until I solve another of Euler’s problems, goodbye!

Posted in Tools | Tagged , , , , , , , , , , | Leave a comment
  • Julia fractal of the day

  • A random quote

    These … tables (values of trignometry functions), constructed by means of new techniques based principally on the calculus of differences, are one of the most beautiful monuments ever erected to science.— Andrien-Marie Legendre

  • Categories

  •  

    May 2012
    MTWTFSS
    « Sep  
     123456
    78910111213
    14151617181920
    21222324252627
    28293031 
    • Events are coming soon, stay tuned!