Skip to content

Benchmarking PHP functions

Often a PHP developer will find themselves needing to know how long a function they are writing takes. Maybe a page seems to be taking too long to load, or maybe they have two different functions that perform the same task and need to see which one performs faster. This is where benchmarking comes in.

I wrote an article comparing echo, print, and printf in terms of speed and wrote a small script to measure each run several times over thousands of iterations. As I started working on other benchmarks, I realized that this script could be made more generalized so as to allow tests to be set up relatively simply. Here is that script as a template.

/*	Set up variables	*/
$testcount = 10;
$iterations = 100000;

for ($x=0;$x< $testcount;$x++)
	{
	$starttime = microtime();
	for ($i=0;$i<$iterations;$i++)
		{
		/*************************
		The test code goes in here
		*************************/
		}
	$endtime = microtime();
	$starttime = explode(" ", $starttime);
	$starttime = $starttime[1] + $starttime[0];
	$endtime = explode(" ", $endtime);
	$endtime = $endtime[1] + $endtime[0];
	$timerecord[$x] = ($endtime - $starttime);
	}

echo "\n";
echo "Test completed\n";
echo "     Test count: ".(number_format($testcount))."\n";
echo "     Iterations: ".(number_format($iterations))."\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 use, simply repace the comments marking where the test code goes with your code. The script defaults to 10 tests of 100,000 iterations each for a total of 1,000,000 total tests. Depending on your test, this may be way too many, or not enough. The two variables $testcount and $iterations allow you to adjust the numbers to fit your needs.

I’ll be using this script on most of my benchmark tests on this site, so hopefully it’ll show the test data in a pretty easy way.

For more information on the functions used in this script, please see the PHP.net pages for arrays, explode, for loops, microtime, and number_format.

Published inProgramming

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *