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 array All of the params passed from $wgProfiler */
37 protected $params = [];
38 /** @var IContextSource Current request context */
39 protected $context = null;
40 /** @var TransactionProfiler */
41 protected $trxProfiler;
43 private $allowOutput = false;
46 private static $instance = null;
49 * @param array $params
51 public function __construct( array $params ) {
52 if ( isset( $params['profileID'] ) ) {
53 $this->profileID
= $params['profileID'];
55 $this->params
= $params;
56 $this->trxProfiler
= new TransactionProfiler();
63 final public static function instance() {
64 if ( self
::$instance === null ) {
65 global $wgProfiler, $wgProfileLimit;
68 'class' => ProfilerStub
::class,
70 'threshold' => $wgProfileLimit,
73 if ( is_array( $wgProfiler ) ) {
74 $params = array_merge( $params, $wgProfiler );
77 $inSample = mt_rand( 0, $params['sampling'] - 1 ) === 0;
78 // wfIsCLI() is not available yet
79 if ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' ||
!$inSample ) {
80 $params['class'] = ProfilerStub
::class;
83 if ( !is_array( $params['output'] ) ) {
84 $params['output'] = [ $params['output'] ];
87 self
::$instance = new $params['class']( $params );
89 return self
::$instance;
93 * Replace the current profiler with $profiler if no non-stub profiler is set
95 * @param Profiler $profiler
99 final public static function replaceStubInstance( Profiler
$profiler ) {
100 if ( self
::$instance && !( self
::$instance instanceof ProfilerStub
) ) {
101 throw new MWException( 'Could not replace non-stub profiler instance.' );
103 self
::$instance = $profiler;
110 public function setProfileID( $id ) {
111 $this->profileID
= $id;
117 public function getProfileID() {
118 if ( $this->profileID
=== false ) {
119 return WikiMap
::getCurrentWikiDbDomain()->getId();
121 return $this->profileID
;
126 * Sets the context for this Profiler
128 * @param IContextSource $context
131 public function setContext( $context ) {
132 $this->context
= $context;
136 * Gets the context for this Profiler
138 * @return IContextSource
141 public function getContext() {
142 if ( $this->context
) {
143 return $this->context
;
145 wfDebug( __METHOD__
. " called and \$context is null. " .
146 "Return RequestContext::getMain(); for sanity\n" );
147 return RequestContext
::getMain();
151 public function profileIn( $functionname ) {
152 wfDeprecated( __METHOD__
, '1.33' );
155 public function profileOut( $functionname ) {
156 wfDeprecated( __METHOD__
, '1.33' );
160 * Mark the start of a custom profiling frame (e.g. DB queries).
161 * The frame ends when the result of this method falls out of scope.
163 * @param string $section
164 * @return ScopedCallback|null
167 abstract public function scopedProfileIn( $section );
170 * @param SectionProfileCallback|null &$section
172 public function scopedProfileOut( SectionProfileCallback
&$section = null ) {
177 * @return TransactionProfiler
180 public function getTransactionProfiler() {
181 return $this->trxProfiler
;
185 * Close opened profiling sections
187 abstract public function close();
190 * Get all usable outputs.
192 * @throws MWException
193 * @return ProfilerOutput[]
196 private function getOutputs() {
198 foreach ( $this->params
['output'] as $outputType ) {
199 // The class may be specified as either the full class name (for
200 // example, 'ProfilerOutputStats') or (for backward compatibility)
201 // the trailing portion of the class name (for example, 'stats').
202 $outputClass = strpos( $outputType, 'ProfilerOutput' ) === false
203 ?
'ProfilerOutput' . ucfirst( $outputType )
205 if ( !class_exists( $outputClass ) ) {
206 throw new MWException( "'$outputType' is an invalid output type" );
208 $outputInstance = new $outputClass( $this, $this->params
);
209 if ( $outputInstance->canUse() ) {
210 $outputs[] = $outputInstance;
217 * Log the data to the backing store for all ProfilerOutput instances that have one
221 public function logData() {
222 $request = $this->getContext()->getRequest();
224 $timeElapsed = $request->getElapsedTime();
225 $timeElapsedThreshold = $this->params
['threshold'];
226 if ( $timeElapsed <= $timeElapsedThreshold ) {
231 foreach ( $this->getOutputs() as $output ) {
232 if ( !$output->logsToOutput() ) {
233 $outputs[] = $output;
238 $stats = $this->getFunctionStats();
239 foreach ( $outputs as $output ) {
240 $output->log( $stats );
246 * Log the data to the script/request output for all ProfilerOutput instances that do so
248 * @throws MWException
251 public function logDataPageOutputOnly() {
252 if ( !$this->allowOutput
) {
257 foreach ( $this->getOutputs() as $output ) {
258 if ( $output->logsToOutput() ) {
259 $outputs[] = $output;
264 $stats = $this->getFunctionStats();
265 foreach ( $outputs as $output ) {
266 $output->log( $stats );
272 * Get the Content-Type for deciding how to format appended profile output.
274 * Disabled by default. Enable via setAllowOutput().
276 * @see ProfilerOutputText
278 * @return string|null Returns null if disabled or no Content-Type found.
280 public function getContentType() {
281 if ( $this->allowOutput
) {
282 foreach ( headers_list() as $header ) {
283 if ( preg_match( '#^content-type: (\w+/\w+);?#i', $header, $m ) ) {
292 * Mark this call as templated or not
294 * @deprecated since 1.34 Use setAllowOutput() instead.
297 public function setTemplated( $t ) {
298 wfDeprecated( __METHOD__
, '1.34' );
299 $this->allowOutput
= ( $t === true );
303 * Was this call as templated or not
305 * @deprecated since 1.34 Use getAllowOutput() instead.
308 public function getTemplated() {
309 wfDeprecated( __METHOD__
, '1.34' );
310 return $this->getAllowOutput();
314 * Enable appending profiles to standard output.
318 public function setAllowOutput() {
319 $this->allowOutput
= true;
323 * Whether appending profiles is allowed.
328 public function getAllowOutput() {
329 return $this->allowOutput
;
333 * Get the aggregated inclusive profiling data for each method
335 * The percent time for each time is based on the current "total" time
336 * used is based on all methods so far. This method can therefore be
337 * called several times in between several profiling calls without the
338 * delays in usage of the profiler skewing the results. A "-total" entry
339 * is always included in the results.
341 * When a call chain involves a method invoked within itself, any
342 * entries for the cyclic invocation should be be demarked with "@".
343 * This makes filtering them out easier and follows the xhprof style.
345 * @return array List of method entries arrays, each having:
346 * - name : method name
347 * - calls : the number of invoking calls
348 * - real : real time elapsed (ms)
349 * - %real : percent real time
350 * - cpu : CPU time elapsed (ms)
351 * - %cpu : percent CPU time
352 * - memory : memory used (bytes)
353 * - %memory : percent memory used
354 * - min_real : min real time in a call (ms)
355 * - max_real : max real time in a call (ms)
358 abstract public function getFunctionStats();
361 * Returns a profiling output to be stored in debug file
365 abstract public function getOutput();