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 if ( is_array( $bench['function'] ) ) {
63 $class = $bench['function'][0];
64 if ( is_object( $class ) ) {
65 $class = get_class( $class );
66 }
67 $name = $class . '::' . $bench['function'][1];
68 } else {
69 $name = strval( $bench['function'] );
70 }
71 $argsText = implode(
72 ', ',
73 array_map(
74 static fn ( $a ) => var_export( $a, true ),
75 $bench['args']
76 )
77 );
78 $index = $shortNames[$name] = ( $shortNames[$name] ?? 0 ) + 1;
79 $shorten = strlen( $argsText ) > 80 || str_contains( $argsText, "\n" );
80 if ( !$shorten ) {
81 $name = "$name($argsText)";
82 }
83 if ( $shorten || $index > 1 ) {
84 $name = "$name@$index";
85 }
86 }
87
88 $normBenchs[$name] = $bench;
89 }
90
91 foreach ( $normBenchs as $name => $bench ) {
92 // Optional setup called outside time measure
93 if ( isset( $bench['setup'] ) ) {
94 $bench['setup']();
95 }
96
97 // Run benchmarks
98 $stat = new RunningStat();
99 for ( $i = 0; $i < $count; $i++ ) {
100 // Setup outside of time measure for each loop
101 if ( isset( $bench['setupEach'] ) ) {
102 $bench['setupEach']();
103 }
104 $t = microtime( true );
105 $bench['function']( ...$bench['args'] );
106 $t = ( microtime( true ) - $t ) * 1000;
107 if ( $verbose ) {
108 $this->verboseRun( $i );
109 }
110 $stat->addObservation( $t );
111 }
112
113 $this->addResult( [
114 'name' => $name,
115 'count' => $stat->getCount(),
116 // Get rate per second from mean (in ms)
117 'rate' => $stat->getMean() == 0 ? INF : ( 1.0 / ( $stat->getMean() / 1000.0 ) ),
118 'total' => $stat->getMean() * $stat->getCount(),
119 'mean' => $stat->getMean(),
120 'max' => $stat->max,
121 'stddev' => $stat->getStdDev(),
122 'usage' => [
123 'mem' => memory_get_usage( true ),
124 'mempeak' => memory_get_peak_usage( true ),
125 ],
126 ] );
127 }
128 }
129
130 public function startBench() {
131 $this->output(
132 sprintf( "Running PHP version %s (%s) on %s %s %s\n\n",
133 phpversion(),
134 php_uname( 'm' ),
135 php_uname( 's' ),
136 php_uname( 'r' ),
137 php_uname( 'v' )
138 )
139 );
140 }
141
142 public function addResult( array $res ) {
143 $ret = sprintf( "%s\n %' 6s: %d\n",
144 $res['name'],
145 'count',
146 $res['count']
147 );
148 $ret .= sprintf( " %' 6s: %8.1f/s\n",
149 'rate',
150 $res['rate']
151 );
152 foreach ( [ 'total', 'mean', 'max', 'stddev' ] as $metric ) {
153 $ret .= sprintf( " %' 6s: %8.2fms\n",
154 $metric,
155 $res[$metric]
156 );
157 }
158
159 foreach ( [
160 'mem' => 'Current memory usage',
161 'mempeak' => 'Peak memory usage'
162 ] as $key => $label ) {
163 $ret .= sprintf( "%' 20s: %s\n",
164 $label,
165 $this->formatSize( $res['usage'][$key] )
166 );
167 }
168
169 $this->output( "$ret\n" );
170 }
171
172 protected function verboseRun( int $iteration ) {
173 $this->output( sprintf( "#%3d - memory: %-10s - peak: %-10s\n",
174 $iteration,
175 $this->formatSize( memory_get_usage( true ) ),
176 $this->formatSize( memory_get_peak_usage( true ) )
177 ) );
178 }
179
190 private function formatSize( $bytes ): string {
191 if ( $bytes >= ( 1024 ** 3 ) ) {
192 return number_format( $bytes / ( 1024 ** 3 ), 2 ) . ' GiB';
193 }
194 if ( $bytes >= ( 1024 ** 2 ) ) {
195 return number_format( $bytes / ( 1024 ** 2 ), 2 ) . ' MiB';
196 }
197 if ( $bytes >= 1024 ) {
198 return number_format( $bytes / 1024, 1 ) . ' KiB';
199 }
200 return $bytes . ' B';
201 }
202
208 protected function loadFile( $file ) {
209 $content = file_get_contents( $file );
210 // Detect GZIP compression header
211 if ( str_starts_with( $content, "\037\213" ) ) {
212 $content = gzdecode( $content );
213 }
214 return $content;
215 }
216}
217
219class_alias( Benchmarker::class, 'Benchmarker' );
if(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:69
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.