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 // wfIsCLI() is not available yet
78 if ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' ||
!$inSample ) {
79 $params['class'] = 'ProfilerStub';
82 if ( !is_array( $params['output'] ) ) {
83 $params['output'] = [ $params['output'] ];
86 self
::$instance = new $params['class']( $params );
88 return self
::$instance;
92 * Replace the current profiler with $profiler if no non-stub profiler is set
94 * @param Profiler $profiler
98 final public static function replaceStubInstance( Profiler
$profiler ) {
99 if ( self
::$instance && !( self
::$instance instanceof ProfilerStub
) ) {
100 throw new MWException( 'Could not replace non-stub profiler instance.' );
102 self
::$instance = $profiler;
109 public function setProfileID( $id ) {
110 $this->profileID
= $id;
116 public function getProfileID() {
117 if ( $this->profileID
=== false ) {
120 return $this->profileID
;
125 * Sets the context for this Profiler
127 * @param IContextSource $context
130 public function setContext( $context ) {
131 $this->context
= $context;
135 * Gets the context for this Profiler
137 * @return IContextSource
140 public function getContext() {
141 if ( $this->context
) {
142 return $this->context
;
144 wfDebug( __METHOD__
. " called and \$context is null. " .
145 "Return RequestContext::getMain(); for sanity\n" );
146 return RequestContext
::getMain();
150 // Kept BC for now, remove when possible
151 public function profileIn( $functionname ) {
154 public function profileOut( $functionname ) {
158 * Mark the start of a custom profiling frame (e.g. DB queries).
159 * The frame ends when the result of this method falls out of scope.
161 * @param string $section
162 * @return ScopedCallback|null
165 abstract public function scopedProfileIn( $section );
168 * @param SectionProfileCallback &$section
170 public function scopedProfileOut( SectionProfileCallback
&$section = null ) {
175 * @return TransactionProfiler
178 public function getTransactionProfiler() {
179 return $this->trxProfiler
;
183 * Close opened profiling sections
185 abstract public function close();
188 * Get all usable outputs.
190 * @throws MWException
191 * @return array Array of ProfilerOutput instances.
194 private function getOutputs() {
196 foreach ( $this->params
['output'] as $outputType ) {
197 // The class may be specified as either the full class name (for
198 // example, 'ProfilerOutputStats') or (for backward compatibility)
199 // the trailing portion of the class name (for example, 'stats').
200 $outputClass = strpos( $outputType, 'ProfilerOutput' ) === false
201 ?
'ProfilerOutput' . ucfirst( $outputType )
203 if ( !class_exists( $outputClass ) ) {
204 throw new MWException( "'$outputType' is an invalid output type" );
206 $outputInstance = new $outputClass( $this, $this->params
);
207 if ( $outputInstance->canUse() ) {
208 $outputs[] = $outputInstance;
215 * Log the data to some store or even the page output
219 public function logData() {
220 $request = $this->getContext()->getRequest();
222 $timeElapsed = $request->getElapsedTime();
223 $timeElapsedThreshold = $this->params
['threshold'];
224 if ( $timeElapsed <= $timeElapsedThreshold ) {
228 $outputs = $this->getOutputs();
233 $stats = $this->getFunctionStats();
234 foreach ( $outputs as $output ) {
235 $output->log( $stats );
240 * Output current data to the page output if configured to do so
242 * @throws MWException
245 public function logDataPageOutputOnly() {
246 foreach ( $this->getOutputs() as $output ) {
247 if ( $output instanceof ProfilerOutputText
) {
248 $stats = $this->getFunctionStats();
249 $output->log( $stats );
255 * Get the content type sent out to the client.
256 * Used for profilers that output instead of store data.
260 public function getContentType() {
261 foreach ( headers_list() as $header ) {
262 if ( preg_match( '#^content-type: (\w+/\w+);?#i', $header, $m ) ) {
270 * Mark this call as templated or not
274 public function setTemplated( $t ) {
275 $this->templated
= $t;
279 * Was this call as templated or not
283 public function getTemplated() {
284 return $this->templated
;
288 * Get the aggregated inclusive profiling data for each method
290 * The percent time for each time is based on the current "total" time
291 * used is based on all methods so far. This method can therefore be
292 * called several times in between several profiling calls without the
293 * delays in usage of the profiler skewing the results. A "-total" entry
294 * is always included in the results.
296 * When a call chain involves a method invoked within itself, any
297 * entries for the cyclic invocation should be be demarked with "@".
298 * This makes filtering them out easier and follows the xhprof style.
300 * @return array List of method entries arrays, each having:
301 * - name : method name
302 * - calls : the number of invoking calls
303 * - real : real time elapsed (ms)
304 * - %real : percent real time
305 * - cpu : CPU time elapsed (ms)
306 * - %cpu : percent CPU time
307 * - memory : memory used (bytes)
308 * - %memory : percent memory used
309 * - min_real : min real time in a call (ms)
310 * - max_real : max real time in a call (ms)
313 abstract public function getFunctionStats();
316 * Returns a profiling output to be stored in debug file
320 abstract public function getOutput();