Template for Benchmarking Multiple Functions at Once in PHP

This is a handy template for running performance 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.

Note that this measures time in nanoseconds because it uses the PHP function hrtime() instead of microtime(). hrtime() is available as of PHP 7.3.0.

This will iterate over each function 1000 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 choose to list just one function, or you can list as many function names as you need to test, separated by comma. And also, include the actual functions somewhere.

PHP >= 7.3.0

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

foreach($functions_to_test as $func) {
    $time_start = hrtime(true);
    for ($i = 1; $i <= $n; $i++) {
    $time_end = hrtime(true);
    $time_total = ($time_end - $time_start);
    echo "Total execution time for $func" . '(): ' . number_format($time_total) . " ns.<br />";

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

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

See more: ,


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: