Benchmark your PHP code

As a developer I often question myself when I have many occurrences of a function that could be replaced by something else. There are often many ways of achieving the same thing and only opinion standing in the way of a decision.

To solve this problem, I often benchmark certain peices of code multiple times to see which comes out the fastest. In this guide/tutorial I will teach you how to benchmark your own code.


The first step is to decide what you want to benchmark, I had trouble in figuring out what to test in this benchmark so in this example I am going to do a simple comparison of using sizeOf inside a for loop and outside a for loop.

The second step is to decide how many times you want to repeat a block of code, if its a larger and more intense block I sugget fewer times, for a shorter block, i recommend more times. In this example I have done 100 times to produce a noticably different output time.

The first part of the code which uses sizeOf inside the for loop:

$start = microtime(true);
for ($i = 0; $i < 100; $i++) {
/* PUT THE CODE TO BENCHMARK BELOW */
 
	$x = range(1,25);
	for ($a=0;$a<sizeOf($x);$a++);
 
/* END OF BENCHMARK CODE */
} unset($start,$i,$x,$a,$s);
printf('%01.2fms'."\n",(microtime(true)-$start)*1000);

Notice, it is important to unset the variables that were set during the test to make it fair.

The second test will be with the sizeOf element outside of the for loop.

$start = microtime(true);
for ($i = 0; $i < 100; $i++) {
/* PUT THE CODE TO BENCHMARK BELOW */
 
	$x = range(1,25);
	$s = sizeOf($x);
	for ($a=0;$a<$s;$a++);
 
/* END OF BENCHMARK CODE */
} unset($start,$i,$x,$a,$s);
printf('%01.2fms'."\n",(microtime(true)-$start)*1000);

Also, notice, the only thing that changed here was the addition of $s = sizeOf($x); and the changed variable in the for loop.

The ouput of this test was quite significant:

2.06ms
0.96ms

As you can see from the results, the sizeOf is best kept outside of the for loop (cached in a variable), so it is not repeated each time.

I hope this guide has helped, I will post the file online later for download and will be doing a more advanced guide on benchmarking in the next few days.

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

No comments yet.

Leave a comment

(required)

(required)