Script for benchmarking PHP functions
Often I find myself needing to know which way of performing a task in PHP is the fastest. The code below let’s you easily test snippets of code to see how long it takes to run.
PHP:
-
/* Set up variables */
-
$testcount = 10;
-
$iterations = 100000;
-
for ($x=0;$x<$testcount;$x++)
-
{
-
for ($i=0;$i<$iterations;$i++)
-
{
-
/*************************
-
The test code goes in here
-
*************************/
-
}
-
$starttime = $starttime[1] + $starttime[0];
-
$endtime = $endtime[1] + $endtime[0];
-
$timerecord[$x] = ($endtime - $starttime);
-
}
-
echo “\n“;
-
echo “Test completed\n“;
-
echo “Results:\n“;
-
for ($q=0;$q<count($timerecord);$q++)
-
{
-
echo “ Time “.($q+1).” = “.$timerecord[$q].” seconds (”.(number_format($timerecord[$q] / $iterations, 15)).“)\n“;
-
}
To test your snippet just place it between the brackets on lines 9-11. As it’s written it will run whatever code you enter 1,000,000 times - 100,000 iterations 10 times. That may be way too many so lines 2 and 3 let you determine how many tests and how many iterations in each test.
I’ve used this code to run quite a few benchmarks and will be posting a few of them here as I get a chance.
Question, Comments...
Do you have more questions. Please either leave a comment below or join us in our new forum.
[...] benchmarking code I’m starting with the benchmarking script I wrote about earlier. It seems to be fairly easy to use and get data quickly. That post is just a framework though. [...]