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!