joshtronic

in Software Development #PHP

Benchmarking PHP code

Have you ever asked yourself, "I wonder which of these blocks of code will run faster?" I know I have and I use a very basic template for setting up these benchmarking experiments. The gist of the script is to run through each block of code n times tracking the amount of time and memory it took to run. It's not nearly as complete as it could be, but it serves as a good enough starting point for doing some quick tests.

<?php

$n = 1000000;

$start_time = microtime(true); $start_mem = memory_get_usage(true);

for ($i = 0; $i < $n; $i++) {

}

$time = microtime(true) - $start_time; $mem = memory_get_usage(true) - $start_mem;

echo "Test 1\t{$time}\t{$mem}\n";

You can duplicate the test block as many times as you need it. Here's a working benchmark I wrote to see if PHP's built-in array_keys function was actually faster than doing a foreach:

<?php

$n = 1000000;

$array = [ 'one' => 'This is the first', 'two' => 'This is the second', 'three' => 'This is the third', 'four' => 'This is the fourth', 'five' => 'This is the fifth', ];

$start_time = microtime(true); $start_mem = memory_get_usage(true);

for ($i = 0; $i < $n; $i++) { unset($array_keys); $array_keys = array_keys($array); }

$time = microtime(true) - $start_time; $mem = memory_get_usage(true) - $start_mem;

echo "array_keys()\t{$time}\t{$mem}\n";

$start_time = microtime(true); $start_mem = memory_get_usage(true);

for ($i = 0; $i < $n; $i++) { unset($array_keys);

foreach ($array as $key => $value) { $array_keys[] = $key; } }

$time = microtime(true) - $start_time; $mem = memory_get_usage(true) - $start_mem;

echo "foreach()\t{$time}\t{$mem}\n";

One improvement would be to track the average time per iteration as well as the fastest and slowest iteration. I went ahead and threw the code in a GitHub gist in case anyone wants to fork and improve upon it.