The Benchmark_Iterate Class
The Benchmark_Iterate class provides two methods for benchmarking a function:
- void run(): Benchmarks a function.
- array get([ $simple_output = false]): Returns the benchmark results. In the results, the code $result[x] represents the execution time of iteration x, $result['iterations'] represents the number of iterations and $result['mean'] represents the mean execution time.
Before attempting to benchmark a complex function, here's a simple example that should clarify the benchmarking process. This example defines a function, and then calls it four times using the
run method. Finally, it outputs the results:
<?php
require_once 'Benchmark/Iterate.php';
//create an instance of the Benchmark_Iterate class
$benchmark = new Benchmark_Iterate;
function example($string) {
print $string . '<br>';
}
//Benchmarks the example function
$benchmark->run(4, 'example', 'Octavia');
//Returns benchmark result
$result = $benchmark->get();
echo 'The number of iterations is '.$result['iterations'].'<br />';
echo 'The mean is: '.$result['mean'];
?>
When you run this application, the output is:
Octavia
Octavia
Octavia
Octavia
The number of iterations is 4
The mean is: 0.000064
With that simple example in hand,
Listing 2 shows a slightly more complex example that applies the Benchmark_Iterate class to the iterative Fibonacci solution, while
Listing 3 applies it to the recursive Fibonacci solution. The programs return these results:
Iterative Result
1 1 2 3 5 8 13 21 34 55 89
The execution time of 1 iteration: 0.000223
The number of iterations is: 1
The mean is: 0.000223
The Recursive Result
1 1 2 3 5 8 13 21 34 55 89
The execution time of 1 iteration is: 0.001135
The number of iterations is: 1
The mean is: 0.001135