3 * Base class for profiling.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
22 * @defgroup Profiler Profiler
24 use Wikimedia\ScopedCallback
;
25 use Wikimedia\Rdbms\TransactionProfiler
;
28 * Profiler base class that defines the interface and some trivial
33 abstract class Profiler
{
34 /** @var string|bool Profiler ID for bucketing data */
35 protected $profileID = false;
36 /** @var bool Whether MediaWiki is in a SkinTemplate output context */
37 protected $templated = false;
38 /** @var array All of the params passed from $wgProfiler */
39 protected $params = [];
40 /** @var IContextSource Current request context */
41 protected $context = null;
42 /** @var TransactionProfiler */
43 protected $trxProfiler;
45 private static $instance = null;
48 * @param array $params
50 public function __construct( array $params ) {
51 if ( isset( $params['profileID'] ) ) {
52 $this->profileID
= $params['profileID'];
54 $this->params
= $params;
55 $this->trxProfiler
= new TransactionProfiler();
62 final public static function instance() {
63 if ( self
::$instance === null ) {
64 global $wgProfiler, $wgProfileLimit;
67 'class' => 'ProfilerStub',
69 'threshold' => $wgProfileLimit,
72 if ( is_array( $wgProfiler ) ) {
73 $params = array_merge( $params, $wgProfiler );
76 $inSample = mt_rand( 0, $params['sampling'] - 1 ) === 0;
77 if ( PHP_SAPI
=== 'cli' ||
!$inSample ) {
78 $params['class'] = 'ProfilerStub';
81 if ( !is_array( $params['output'] ) ) {
82 $params['output'] = [ $params['output'] ];
85 self
::$instance = new $params['class']( $params );
87 return self
::$instance;
91 * Replace the current profiler with $profiler if no non-stub profiler is set
93 * @param Profiler $profiler
97 final public static function replaceStubInstance( Profiler
$profiler ) {
98 if ( self
::$instance && !( self
::$instance instanceof ProfilerStub
) ) {
99 throw new MWException( 'Could not replace non-stub profiler instance.' );
101 self
::$instance = $profiler;
108 public function setProfileID( $id ) {
109 $this->profileID
= $id;
115 public function getProfileID() {
116 if ( $this->profileID
=== false ) {
119 return $this->profileID
;
124 * Sets the context for this Profiler
126 * @param IContextSource $context
129 public function setContext( $context ) {
130 $this->context
= $context;
134 * Gets the context for this Profiler
136 * @return IContextSource
139 public function getContext() {
140 if ( $this->context
) {
141 return $this->context
;
143 wfDebug( __METHOD__
. " called and \$context is null. " .
144 "Return RequestContext::getMain(); for sanity\n" );
145 return RequestContext
::getMain();
149 // Kept BC for now, remove when possible
150 public function profileIn( $functionname ) {
153 public function profileOut( $functionname ) {
157 * Mark the start of a custom profiling frame (e.g. DB queries).
158 * The frame ends when the result of this method falls out of scope.
160 * @param string $section
161 * @return ScopedCallback|null
164 abstract public function scopedProfileIn( $section );
167 * @param SectionProfileCallback &$section
169 public function scopedProfileOut( SectionProfileCallback
&$section = null ) {
174 * @return TransactionProfiler
177 public function getTransactionProfiler() {
178 return $this->trxProfiler
;
182 * Close opened profiling sections
184 abstract public function close();
187 * Get all usable outputs.
189 * @throws MWException
190 * @return array Array of ProfilerOutput instances.
193 private function getOutputs() {
195 foreach ( $this->params
['output'] as $outputType ) {
196 // The class may be specified as either the full class name (for
197 // example, 'ProfilerOutputStats') or (for backward compatibility)
198 // the trailing portion of the class name (for example, 'stats').
199 $outputClass = strpos( $outputType, 'ProfilerOutput' ) === false
200 ?
'ProfilerOutput' . ucfirst( $outputType )
202 if ( !class_exists( $outputClass ) ) {
203 throw new MWException( "'$outputType' is an invalid output type" );
205 $outputInstance = new $outputClass( $this, $this->params
);
206 if ( $outputInstance->canUse() ) {
207 $outputs[] = $outputInstance;
214 * Log the data to some store or even the page output
218 public function logData() {
219 $request = $this->getContext()->getRequest();
221 $timeElapsed = $request->getElapsedTime();
222 $timeElapsedThreshold = $this->params
['threshold'];
223 if ( $timeElapsed <= $timeElapsedThreshold ) {
227 $outputs = $this->getOutputs();
232 $stats = $this->getFunctionStats();
233 foreach ( $outputs as $output ) {
234 $output->log( $stats );
239 * Output current data to the page output if configured to do so
241 * @throws MWException
244 public function logDataPageOutputOnly() {
245 foreach ( $this->getOutputs() as $output ) {
246 if ( $output instanceof ProfilerOutputText
) {
247 $stats = $this->getFunctionStats();
248 $output->log( $stats );
254 * Get the content type sent out to the client.
255 * Used for profilers that output instead of store data.
259 public function getContentType() {
260 foreach ( headers_list() as $header ) {
261 if ( preg_match( '#^content-type: (\w+/\w+);?#i', $header, $m ) ) {
269 * Mark this call as templated or not
273 public function setTemplated( $t ) {
274 $this->templated
= $t;
278 * Was this call as templated or not
282 public function getTemplated() {
283 return $this->templated
;
287 * Get the aggregated inclusive profiling data for each method
289 * The percent time for each time is based on the current "total" time
290 * used is based on all methods so far. This method can therefore be
291 * called several times in between several profiling calls without the
292 * delays in usage of the profiler skewing the results. A "-total" entry
293 * is always included in the results.
295 * When a call chain involves a method invoked within itself, any
296 * entries for the cyclic invocation should be be demarked with "@".
297 * This makes filtering them out easier and follows the xhprof style.
299 * @return array List of method entries arrays, each having:
300 * - name : method name
301 * - calls : the number of invoking calls
302 * - real : real time elapsed (ms)
303 * - %real : percent real time
304 * - cpu : CPU time elapsed (ms)
305 * - %cpu : percent CPU time
306 * - memory : memory used (bytes)
307 * - %memory : percent memory used
308 * - min_real : min real time in a call (ms)
309 * - max_real : max real time in a call (ms)
312 abstract public function getFunctionStats();
315 * Returns a profiling output to be stored in debug file
319 abstract public function getOutput();