Software Developer

Template for Benchmarking Multiple Functions at Once in PHP

This is a handy template for running speed tests on your own PHP functions. (This would, of course, also work for benchmarking PHP’s own native functions, but I use this for testing my own random functions. You could also benchmark one of your own functions against a PHP built-in function.)

This is useful for comparing 2 or more functions to see which one is faster.

This will iterate over each function 100000 times. You can change the number of iterations on line 1.

Mandatory edit to make:
This template is an example that benchmarks 2 functions named: myFunction and myOtherFunction. You must replace these function names on line 2 with the names of your own functions that you want to benchmark. You can list as many function names as you need to test, separated by comma. And also, include the actual functions somewhere.

$n = 100000;
$functions_to_test = array('myFunction', 'myOtherFunction');

foreach($functions_to_test as $func) {
    $time_start = microtime(true);
    for ($i = 1; $i <= $n; $i++) {
        $func();
    }
    $time_end = microtime(true);
    $time_total = ($time_end - $time_start)*1000;// milliseconds
    echo "Total execution time for $func" . '(): ' . number_format($time_total, 1) . " ms.<br />";
}

After going through all the iterations, this will print out the total execution time for each function, in milliseconds. Here is an example output:

Total execution time for myFunction(): 263.2 ms.
Total execution time for myOtherFunction(): 290.2 ms.

By

Questions and Comments are Welcome

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this:

[code]

YOUR CODE HERE 

[/code]