MediaWiki master
Benchmarker.php
Go to the documentation of this file.
1<?php
15namespace MediaWiki\Maintenance;
16
17use Wikimedia\RunningStat;
18
19// @codeCoverageIgnoreStart
20require_once __DIR__ . '/../Maintenance.php';
21// @codeCoverageIgnoreEnd
22
28abstract class Benchmarker extends Maintenance {
30 protected $defaultCount = 100;
31
32 public function __construct() {
33 parent::__construct();
34 $this->addOption( 'count', "How many times to run a benchmark. Default: {$this->defaultCount}", false, true );
35 $this->addOption( 'verbose', 'Verbose logging of resource usage', false, false, 'v' );
36 }
37
38 public function bench( array $benchs ) {
39 $this->startBench();
40 $count = $this->getOption( 'count', $this->defaultCount );
41 $verbose = $this->hasOption( 'verbose' );
42
43 $normBenchs = [];
44 $shortNames = [];
45
46 // Normalise
47 foreach ( $benchs as $key => $bench ) {
48 // Shortcut for simple functions
49 if ( is_callable( $bench ) ) {
50 $bench = [ 'function' => $bench ];
51 }
52
53 // Default to no arguments
54 if ( !isset( $bench['args'] ) ) {
55 $bench['args'] = [];
56 }
57
58 // Name defaults to name of called function
59 if ( is_string( $key ) ) {
60 $name = $key;
61 } else {
62 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
63 if ( is_array( $bench['function'] ) ) {
64 $class = $bench['function'][0];
65 if ( is_object( $class ) ) {
66 $class = get_class( $class );
67 }
68 $name = $class . '::' . $bench['function'][1];
69 } else {
70 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
71 $name = strval( $bench['function'] );
72 }
73 $argsText = implode(
74 ', ',
75 array_map(
76 static function ( $a ) {
77 return var_export( $a, true );
78 },
79 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
80 $bench['args']
81 )
82 );
83 $index = $shortNames[$name] = ( $shortNames[$name] ?? 0 ) + 1;
84 $shorten = strlen( $argsText ) > 80 || str_contains( $argsText, "\n" );
85 if ( !$shorten ) {
86 $name = "$name($argsText)";
87 }
88 if ( $shorten || $index > 1 ) {
89 $name = "$name@$index";
90 }
91 }
92
93 $normBenchs[$name] = $bench;
94 }
95
96 foreach ( $normBenchs as $name => $bench ) {
97 // Optional setup called outside time measure
98 if ( isset( $bench['setup'] ) ) {
99 $bench['setup']();
100 }
101
102 // Run benchmarks
103 $stat = new RunningStat();
104 for ( $i = 0; $i < $count; $i++ ) {
105 // Setup outside of time measure for each loop
106 if ( isset( $bench['setupEach'] ) ) {
107 $bench['setupEach']();
108 }
109 $t = microtime( true );
110 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
111 $bench['function']( ...$bench['args'] );
112 $t = ( microtime( true ) - $t ) * 1000;
113 if ( $verbose ) {
114 $this->verboseRun( $i );
115 }
116 $stat->addObservation( $t );
117 }
118
119 $this->addResult( [
120 'name' => $name,
121 'count' => $stat->getCount(),
122 // Get rate per second from mean (in ms)
123 'rate' => $stat->getMean() == 0 ? INF : ( 1.0 / ( $stat->getMean() / 1000.0 ) ),
124 'total' => $stat->getMean() * $stat->getCount(),
125 'mean' => $stat->getMean(),
126 'max' => $stat->max,
127 'stddev' => $stat->getStdDev(),
128 'usage' => [
129 'mem' => memory_get_usage( true ),
130 'mempeak' => memory_get_peak_usage( true ),
131 ],
132 ] );
133 }
134 }
135
136 public function startBench() {
137 $this->output(
138 sprintf( "Running PHP version %s (%s) on %s %s %s\n\n",
139 phpversion(),
140 php_uname( 'm' ),
141 php_uname( 's' ),
142 php_uname( 'r' ),
143 php_uname( 'v' )
144 )
145 );
146 }
147
148 public function addResult( array $res ) {
149 $ret = sprintf( "%s\n %' 6s: %d\n",
150 $res['name'],
151 'count',
152 $res['count']
153 );
154 $ret .= sprintf( " %' 6s: %8.1f/s\n",
155 'rate',
156 $res['rate']
157 );
158 foreach ( [ 'total', 'mean', 'max', 'stddev' ] as $metric ) {
159 $ret .= sprintf( " %' 6s: %8.2fms\n",
160 $metric,
161 $res[$metric]
162 );
163 }
164
165 foreach ( [
166 'mem' => 'Current memory usage',
167 'mempeak' => 'Peak memory usage'
168 ] as $key => $label ) {
169 $ret .= sprintf( "%' 20s: %s\n",
170 $label,
171 $this->formatSize( $res['usage'][$key] )
172 );
173 }
174
175 $this->output( "$ret\n" );
176 }
177
178 protected function verboseRun( int $iteration ) {
179 $this->output( sprintf( "#%3d - memory: %-10s - peak: %-10s\n",
180 $iteration,
181 $this->formatSize( memory_get_usage( true ) ),
182 $this->formatSize( memory_get_peak_usage( true ) )
183 ) );
184 }
185
196 private function formatSize( $bytes ): string {
197 if ( $bytes >= ( 1024 ** 3 ) ) {
198 return number_format( $bytes / ( 1024 ** 3 ), 2 ) . ' GiB';
199 }
200 if ( $bytes >= ( 1024 ** 2 ) ) {
201 return number_format( $bytes / ( 1024 ** 2 ), 2 ) . ' MiB';
202 }
203 if ( $bytes >= 1024 ) {
204 return number_format( $bytes / 1024, 1 ) . ' KiB';
205 }
206 return $bytes . ' B';
207 }
208
214 protected function loadFile( $file ) {
215 $content = file_get_contents( $file );
216 // Detect GZIP compression header
217 if ( str_starts_with( $content, "\037\213" ) ) {
218 $content = gzdecode( $content );
219 }
220 return $content;
221 }
222}
223
225class_alias( Benchmarker::class, 'Benchmarker' );
if(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:68
Base class for benchmark scripts.
__construct()
Default constructor.
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
output( $out, $channel=null)
Throw some output to the user.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
hasOption( $name)
Checks to see if a particular option was set.
getOption( $name, $default=null)
Get an option, or return the default.
Update the CREDITS list by merging in the list of git commit authors.