Benchmark_Iterateクラス
Benchmark_Iterateクラスには、関数のベンチマークに使用できるメソッドが2つあります。
void run()― 関数のベンチマークを行います。array get([ $simple_output = false])― ベンチマーク結果を配列として返します。結果配列で、$result[x]は反復xの実行時間を示します。$result['iterations']は反復回数、また$result['mean']は平均実行時間を示します。
複雑な関数のベンチマークを行う前に、まず簡単な例を見てみましょう。ベンチマークのプロセスがよくわかるはずです。この例では、関数を定義して、その関数をrunメソッドで4回呼び出します。最後に結果を出力します。
<?php require_once 'Benchmark/Iterate.php'; //create an instance of 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']; ?>
このアプリケーションを実行すると、結果は次のようになります。
Octavia Octavia Octavia Octavia The number of iterations is 4 The mean is: 0.000064
この簡単な例を理解したところで、今度は少し複雑な例を見てみましょう。リスト2では、フィボナッチ数列を反復で求める処理にBenchmark_Iterateクラスを適用しています。一方、リスト3では、フィボナッチ数列を再帰で求める処理にBenchmark_Iterateクラスを適用しています。各プログラムの実行結果は次のとおりです。
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
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
<?php require_once 'Benchmark/Iterate.php'; //create an instance of the Benchmark_Iterate class $benchmark = new Benchmark_Iterate; //this function implements the iterative solution //for the Fibonacci problem function fibonacci(){ $a=0;$b=1; echo $b.' '; for ($i = 0; $i < 10; $i++) { $s=$a+$b; echo $s.' '; $a=$b; $b=$s; } echo '<br />'; } //Benchmarks the Fibonacci function $benchmark->run(1, 'fibonacci'); //Returns benchmark result $result = $benchmark->get(); //Returns execution time of iteration 1 using the $result variabile echo 'The execution time of 1 iteration is: '.$result[1].'<br />'; //Returns the number of iterations using the $result variabile echo 'The number of iterations is: '.$result['iterations'].'<br />'; //Returns the mean execution time echo 'The mean is: '.$result['mean']; ?>
<?php require_once 'Benchmark/Iterate.php'; //create an instance of the Benchmark_Iterate class $benchmark = new Benchmark_Iterate; echo 'The first 10 terms of the Fibonacci series are: '; //this function implements the recursive solution //for the fibonacci problem function fibonacci($n){ if(($n>=0)and($n<2)) {return 1;} else {return fibonacci($n-1)+fibonacci($n-2);} } for ($i = 0; $i <= 10; $i++) { echo fibonacci($i).' '; } //Benchmarks the Fibonacci function $benchmark->run(2, 'fibonacci'); //Returns benchmark result $result = $benchmark->get(); echo 'The execution time of 1 iteration is: '.$result[1].'<br />'; echo '<br />'.'The number of iterations is: ' .$result['iterations'].'<br />'; echo 'The mean is: '.$result['mean']; ?>
