822f1a6a8b8577c5052dcd485255f8c794620eba
[lhc/web/wiklou.git] / maintenance / benchmarks / Benchmarker.php
1 <?php
2 /**
3 * @defgroup Benchmark Benchmark
4 * @ingroup Maintenance
5 */
6
7 /**
8 * Create a doxygen subgroup of Maintenance for benchmarks
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 * http://www.gnu.org/copyleft/gpl.html
24 *
25 * @todo Report PHP version, OS ..
26 * @file
27 * @ingroup Benchmark
28 */
29
30 require_once( __DIR__ . '/../Maintenance.php' );
31 abstract class Benchmarker extends Maintenance {
32 private $results;
33
34 public function __construct() {
35 parent::__construct();
36 $this->addOption( 'count', "How many time to run a benchmark", false, true );
37 }
38
39 public function bench( array $benchs ) {
40 $bench_number = 0;
41 $count = $this->getOption( 'count', 100 );
42
43 foreach( $benchs as $bench ) {
44 // handle empty args
45 if(!array_key_exists( 'args', $bench )) {
46 $bench['args'] = array();
47 }
48
49 $bench_number++;
50 $start = wfTime();
51 for( $i=0; $i<$count; $i++ ) {
52 call_user_func_array( $bench['function'], $bench['args'] );
53 }
54 $delta = wfTime() - $start;
55
56 // function passed as a callback
57 if( is_array( $bench['function'] ) ) {
58 $ret = get_class( $bench['function'][0] ). '->' . $bench['function'][1];
59 $bench['function'] = $ret;
60 }
61
62 $this->results[$bench_number] = array(
63 'function' => $bench['function'],
64 'arguments' => $bench['args'],
65 'count' => $count,
66 'delta' => $delta,
67 'average' => $delta / $count,
68 );
69 }
70 }
71
72 public function getFormattedResults( ) {
73 $ret = '';
74 foreach( $this->results as $res ) {
75 // show function with args
76 $ret .= sprintf( "%s times: function %s(%s) :\n",
77 $res['count'],
78 $res['function'],
79 join( ', ', $res['arguments'] )
80 );
81 $ret .= sprintf( " %6.2fms (%6.2fms each)\n",
82 $res['delta'] * 1000,
83 $res['average'] * 1000
84 );
85 }
86 return $ret;
87 }
88 }