Merge "Export: Use BCP 47 language code for attribute xml:lang"
[lhc/web/wiklou.git] / maintenance / benchmarks / Benchmarker.php
1 <?php
2 /**
3 * @defgroup Benchmark Benchmark
4 * @ingroup Maintenance
5 */
6
7 /**
8 * Base code for benchmark scripts.
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 * @file
26 * @ingroup Benchmark
27 */
28
29 require_once __DIR__ . '/../Maintenance.php';
30
31 /**
32 * Base class for benchmark scripts.
33 *
34 * @ingroup Benchmark
35 */
36 abstract class Benchmarker extends Maintenance {
37 private $results;
38
39 public function __construct() {
40 parent::__construct();
41 $this->addOption( 'count', "How many times to run a benchmark", false, true );
42 }
43
44 public function bench( array $benchs ) {
45 $bench_number = 0;
46 $count = $this->getOption( 'count', 100 );
47
48 foreach ( $benchs as $bench ) {
49 // handle empty args
50 if ( !array_key_exists( 'args', $bench ) ) {
51 $bench['args'] = [];
52 }
53
54 $bench_number++;
55 $start = microtime( true );
56 for ( $i = 0; $i < $count; $i++ ) {
57 call_user_func_array( $bench['function'], $bench['args'] );
58 }
59 $delta = microtime( true ) - $start;
60
61 // function passed as a callback
62 if ( is_array( $bench['function'] ) ) {
63 $ret = get_class( $bench['function'][0] ) . '->' . $bench['function'][1];
64 $bench['function'] = $ret;
65 }
66
67 $this->results[$bench_number] = [
68 'function' => $bench['function'],
69 'arguments' => $bench['args'],
70 'count' => $count,
71 'delta' => $delta,
72 'average' => $delta / $count,
73 ];
74 }
75 }
76
77 public function getFormattedResults() {
78 $ret = sprintf( "Running PHP version %s (%s) on %s %s %s\n\n",
79 phpversion(),
80 php_uname( 'm' ),
81 php_uname( 's' ),
82 php_uname( 'r' ),
83 php_uname( 'v' )
84 );
85 foreach ( $this->results as $res ) {
86 // show function with args
87 $ret .= sprintf( "%s times: function %s(%s) :\n",
88 $res['count'],
89 $res['function'],
90 implode( ', ', $res['arguments'] )
91 );
92 $ret .= sprintf( " %6.2fms (%6.2fms each)\n",
93 $res['delta'] * 1000,
94 $res['average'] * 1000
95 );
96 }
97
98 return $ret;
99 }
100 }