summaryrefslogtreecommitdiff
path: root/www/wiki/includes/profiler
diff options
context:
space:
mode:
authorYaco <franco@reevo.org>2020-06-04 11:01:00 -0300
committerYaco <franco@reevo.org>2020-06-04 11:01:00 -0300
commitfc7369835258467bf97eb64f184b93691f9a9fd5 (patch)
treedaabd60089d2dd76d9f5fb416b005fbe159c799d /www/wiki/includes/profiler
first commit
Diffstat (limited to 'www/wiki/includes/profiler')
-rw-r--r--www/wiki/includes/profiler/Profiler.php321
-rw-r--r--www/wiki/includes/profiler/ProfilerSectionOnly.php103
-rw-r--r--www/wiki/includes/profiler/ProfilerStub.php48
-rw-r--r--www/wiki/includes/profiler/ProfilerXhprof.php239
-rw-r--r--www/wiki/includes/profiler/SectionProfiler.php524
-rw-r--r--www/wiki/includes/profiler/output/ProfilerOutput.php56
-rw-r--r--www/wiki/includes/profiler/output/ProfilerOutputDb.php106
-rw-r--r--www/wiki/includes/profiler/output/ProfilerOutputDump.php55
-rw-r--r--www/wiki/includes/profiler/output/ProfilerOutputStats.php56
-rw-r--r--www/wiki/includes/profiler/output/ProfilerOutputText.php77
10 files changed, 1585 insertions, 0 deletions
diff --git a/www/wiki/includes/profiler/Profiler.php b/www/wiki/includes/profiler/Profiler.php
new file mode 100644
index 00000000..d02011fa
--- /dev/null
+++ b/www/wiki/includes/profiler/Profiler.php
@@ -0,0 +1,321 @@
+<?php
+/**
+ * Base class for profiling.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ *
+ * @file
+ * @ingroup Profiler
+ * @defgroup Profiler Profiler
+ */
+use Wikimedia\ScopedCallback;
+use Wikimedia\Rdbms\TransactionProfiler;
+
+/**
+ * Profiler base class that defines the interface and some trivial
+ * functionality
+ *
+ * @ingroup Profiler
+ */
+abstract class Profiler {
+ /** @var string|bool Profiler ID for bucketing data */
+ protected $profileID = false;
+ /** @var bool Whether MediaWiki is in a SkinTemplate output context */
+ protected $templated = false;
+ /** @var array All of the params passed from $wgProfiler */
+ protected $params = [];
+ /** @var IContextSource Current request context */
+ protected $context = null;
+ /** @var TransactionProfiler */
+ protected $trxProfiler;
+ /** @var Profiler */
+ private static $instance = null;
+
+ /**
+ * @param array $params
+ */
+ public function __construct( array $params ) {
+ if ( isset( $params['profileID'] ) ) {
+ $this->profileID = $params['profileID'];
+ }
+ $this->params = $params;
+ $this->trxProfiler = new TransactionProfiler();
+ }
+
+ /**
+ * Singleton
+ * @return Profiler
+ */
+ final public static function instance() {
+ if ( self::$instance === null ) {
+ global $wgProfiler, $wgProfileLimit;
+
+ $params = [
+ 'class' => ProfilerStub::class,
+ 'sampling' => 1,
+ 'threshold' => $wgProfileLimit,
+ 'output' => [],
+ ];
+ if ( is_array( $wgProfiler ) ) {
+ $params = array_merge( $params, $wgProfiler );
+ }
+
+ $inSample = mt_rand( 0, $params['sampling'] - 1 ) === 0;
+ // wfIsCLI() is not available yet
+ if ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' || !$inSample ) {
+ $params['class'] = ProfilerStub::class;
+ }
+
+ if ( !is_array( $params['output'] ) ) {
+ $params['output'] = [ $params['output'] ];
+ }
+
+ self::$instance = new $params['class']( $params );
+ }
+ return self::$instance;
+ }
+
+ /**
+ * Replace the current profiler with $profiler if no non-stub profiler is set
+ *
+ * @param Profiler $profiler
+ * @throws MWException
+ * @since 1.25
+ */
+ final public static function replaceStubInstance( Profiler $profiler ) {
+ if ( self::$instance && !( self::$instance instanceof ProfilerStub ) ) {
+ throw new MWException( 'Could not replace non-stub profiler instance.' );
+ } else {
+ self::$instance = $profiler;
+ }
+ }
+
+ /**
+ * @param string $id
+ */
+ public function setProfileID( $id ) {
+ $this->profileID = $id;
+ }
+
+ /**
+ * @return string
+ */
+ public function getProfileID() {
+ if ( $this->profileID === false ) {
+ return wfWikiID();
+ } else {
+ return $this->profileID;
+ }
+ }
+
+ /**
+ * Sets the context for this Profiler
+ *
+ * @param IContextSource $context
+ * @since 1.25
+ */
+ public function setContext( $context ) {
+ $this->context = $context;
+ }
+
+ /**
+ * Gets the context for this Profiler
+ *
+ * @return IContextSource
+ * @since 1.25
+ */
+ public function getContext() {
+ if ( $this->context ) {
+ return $this->context;
+ } else {
+ wfDebug( __METHOD__ . " called and \$context is null. " .
+ "Return RequestContext::getMain(); for sanity\n" );
+ return RequestContext::getMain();
+ }
+ }
+
+ // Kept BC for now, remove when possible
+ public function profileIn( $functionname ) {
+ }
+
+ public function profileOut( $functionname ) {
+ }
+
+ /**
+ * Mark the start of a custom profiling frame (e.g. DB queries).
+ * The frame ends when the result of this method falls out of scope.
+ *
+ * @param string $section
+ * @return ScopedCallback|null
+ * @since 1.25
+ */
+ abstract public function scopedProfileIn( $section );
+
+ /**
+ * @param SectionProfileCallback &$section
+ */
+ public function scopedProfileOut( SectionProfileCallback &$section = null ) {
+ $section = null;
+ }
+
+ /**
+ * @return TransactionProfiler
+ * @since 1.25
+ */
+ public function getTransactionProfiler() {
+ return $this->trxProfiler;
+ }
+
+ /**
+ * Close opened profiling sections
+ */
+ abstract public function close();
+
+ /**
+ * Get all usable outputs.
+ *
+ * @throws MWException
+ * @return ProfilerOutput[]
+ * @since 1.25
+ */
+ private function getOutputs() {
+ $outputs = [];
+ foreach ( $this->params['output'] as $outputType ) {
+ // The class may be specified as either the full class name (for
+ // example, 'ProfilerOutputStats') or (for backward compatibility)
+ // the trailing portion of the class name (for example, 'stats').
+ $outputClass = strpos( $outputType, 'ProfilerOutput' ) === false
+ ? 'ProfilerOutput' . ucfirst( $outputType )
+ : $outputType;
+ if ( !class_exists( $outputClass ) ) {
+ throw new MWException( "'$outputType' is an invalid output type" );
+ }
+ $outputInstance = new $outputClass( $this, $this->params );
+ if ( $outputInstance->canUse() ) {
+ $outputs[] = $outputInstance;
+ }
+ }
+ return $outputs;
+ }
+
+ /**
+ * Log the data to some store or even the page output
+ *
+ * @since 1.25
+ */
+ public function logData() {
+ $request = $this->getContext()->getRequest();
+
+ $timeElapsed = $request->getElapsedTime();
+ $timeElapsedThreshold = $this->params['threshold'];
+ if ( $timeElapsed <= $timeElapsedThreshold ) {
+ return;
+ }
+
+ $outputs = $this->getOutputs();
+ if ( !$outputs ) {
+ return;
+ }
+
+ $stats = $this->getFunctionStats();
+ foreach ( $outputs as $output ) {
+ $output->log( $stats );
+ }
+ }
+
+ /**
+ * Output current data to the page output if configured to do so
+ *
+ * @throws MWException
+ * @since 1.26
+ */
+ public function logDataPageOutputOnly() {
+ foreach ( $this->getOutputs() as $output ) {
+ if ( $output instanceof ProfilerOutputText ) {
+ $stats = $this->getFunctionStats();
+ $output->log( $stats );
+ }
+ }
+ }
+
+ /**
+ * Get the content type sent out to the client.
+ * Used for profilers that output instead of store data.
+ * @return string
+ * @since 1.25
+ */
+ public function getContentType() {
+ foreach ( headers_list() as $header ) {
+ if ( preg_match( '#^content-type: (\w+/\w+);?#i', $header, $m ) ) {
+ return $m[1];
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Mark this call as templated or not
+ *
+ * @param bool $t
+ */
+ public function setTemplated( $t ) {
+ $this->templated = $t;
+ }
+
+ /**
+ * Was this call as templated or not
+ *
+ * @return bool
+ */
+ public function getTemplated() {
+ return $this->templated;
+ }
+
+ /**
+ * Get the aggregated inclusive profiling data for each method
+ *
+ * The percent time for each time is based on the current "total" time
+ * used is based on all methods so far. This method can therefore be
+ * called several times in between several profiling calls without the
+ * delays in usage of the profiler skewing the results. A "-total" entry
+ * is always included in the results.
+ *
+ * When a call chain involves a method invoked within itself, any
+ * entries for the cyclic invocation should be be demarked with "@".
+ * This makes filtering them out easier and follows the xhprof style.
+ *
+ * @return array List of method entries arrays, each having:
+ * - name : method name
+ * - calls : the number of invoking calls
+ * - real : real time elapsed (ms)
+ * - %real : percent real time
+ * - cpu : CPU time elapsed (ms)
+ * - %cpu : percent CPU time
+ * - memory : memory used (bytes)
+ * - %memory : percent memory used
+ * - min_real : min real time in a call (ms)
+ * - max_real : max real time in a call (ms)
+ * @since 1.25
+ */
+ abstract public function getFunctionStats();
+
+ /**
+ * Returns a profiling output to be stored in debug file
+ *
+ * @return string
+ */
+ abstract public function getOutput();
+}
diff --git a/www/wiki/includes/profiler/ProfilerSectionOnly.php b/www/wiki/includes/profiler/ProfilerSectionOnly.php
new file mode 100644
index 00000000..a7bc1375
--- /dev/null
+++ b/www/wiki/includes/profiler/ProfilerSectionOnly.php
@@ -0,0 +1,103 @@
+<?php
+/**
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ *
+ * @file
+ */
+
+/**
+ * Profiler that only tracks explicit profiling sections
+ *
+ * @code
+ * $wgProfiler['class'] = ProfilerSectionOnly::class;
+ * $wgProfiler['output'] = 'text';
+ * $wgProfiler['visible'] = true;
+ * @endcode
+ *
+ * @ingroup Profiler
+ * @since 1.25
+ */
+class ProfilerSectionOnly extends Profiler {
+ /** @var SectionProfiler */
+ protected $sprofiler;
+
+ public function __construct( array $params = [] ) {
+ parent::__construct( $params );
+ $this->sprofiler = new SectionProfiler();
+ }
+
+ public function scopedProfileIn( $section ) {
+ return $this->sprofiler->scopedProfileIn( $section );
+ }
+
+ public function close() {
+ }
+
+ public function getFunctionStats() {
+ return $this->sprofiler->getFunctionStats();
+ }
+
+ public function getOutput() {
+ return $this->getFunctionReport();
+ }
+
+ /**
+ * Get a report of profiled functions sorted by inclusive wall clock time
+ * in descending order.
+ *
+ * Each line of the report includes this data:
+ * - Function name
+ * - Number of times function was called
+ * - Total wall clock time spent in function in microseconds
+ * - Minimum wall clock time spent in function in microseconds
+ * - Average wall clock time spent in function in microseconds
+ * - Maximum wall clock time spent in function in microseconds
+ * - Percentage of total wall clock time spent in function
+ * - Total delta of memory usage from start to end of function in bytes
+ *
+ * @return string
+ */
+ protected function getFunctionReport() {
+ $data = $this->getFunctionStats();
+ usort( $data, function ( $a, $b ) {
+ if ( $a['real'] === $b['real'] ) {
+ return 0;
+ }
+ return ( $a['real'] > $b['real'] ) ? -1 : 1; // descending
+ } );
+
+ $width = 140;
+ $nameWidth = $width - 65;
+ $format = "%-{$nameWidth}s %6d %9d %9d %9d %9d %7.3f%% %9d";
+ $out = [];
+ $out[] = sprintf( "%-{$nameWidth}s %6s %9s %9s %9s %9s %7s %9s",
+ 'Name', 'Calls', 'Total', 'Min', 'Each', 'Max', '%', 'Mem'
+ );
+ foreach ( $data as $stats ) {
+ $out[] = sprintf( $format,
+ $stats['name'],
+ $stats['calls'],
+ $stats['real'] * 1000,
+ $stats['min_real'] * 1000,
+ $stats['real'] / $stats['calls'] * 1000,
+ $stats['max_real'] * 1000,
+ $stats['%real'],
+ $stats['memory']
+ );
+ }
+ return implode( "\n", $out );
+ }
+}
diff --git a/www/wiki/includes/profiler/ProfilerStub.php b/www/wiki/includes/profiler/ProfilerStub.php
new file mode 100644
index 00000000..1017e446
--- /dev/null
+++ b/www/wiki/includes/profiler/ProfilerStub.php
@@ -0,0 +1,48 @@
+<?php
+/**
+ * Stub profiling functions.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ *
+ * @file
+ * @ingroup Profiler
+ */
+
+/**
+ * Stub profiler that does nothing
+ *
+ * @ingroup Profiler
+ */
+class ProfilerStub extends Profiler {
+ public function scopedProfileIn( $section ) {
+ return null; // no-op
+ }
+
+ public function getFunctionStats() {
+ }
+
+ public function getOutput() {
+ }
+
+ public function close() {
+ }
+
+ public function logData() {
+ }
+
+ public function logDataPageOutputOnly() {
+ }
+}
diff --git a/www/wiki/includes/profiler/ProfilerXhprof.php b/www/wiki/includes/profiler/ProfilerXhprof.php
new file mode 100644
index 00000000..ffa441ed
--- /dev/null
+++ b/www/wiki/includes/profiler/ProfilerXhprof.php
@@ -0,0 +1,239 @@
+<?php
+/**
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ *
+ * @file
+ */
+
+/**
+ * Profiler wrapper for XHProf extension.
+ *
+ * @code
+ * $wgProfiler['class'] = ProfilerXhprof::class;
+ * $wgProfiler['flags'] = XHPROF_FLAGS_NO_BUILTINS;
+ * $wgProfiler['output'] = 'text';
+ * $wgProfiler['visible'] = true;
+ * @endcode
+ *
+ * @code
+ * $wgProfiler['class'] = ProfilerXhprof::class;
+ * $wgProfiler['flags'] = XHPROF_FLAGS_CPU | XHPROF_FLAGS_MEMORY | XHPROF_FLAGS_NO_BUILTINS;
+ * $wgProfiler['output'] = 'udp';
+ * @endcode
+ *
+ * ProfilerXhprof profiles all functions using the XHProf PHP extenstion.
+ * For PHP5 users, this extension can be installed via PECL or your operating
+ * system's package manager. XHProf support is built into HHVM.
+ *
+ * To restrict the functions for which profiling data is collected, you can
+ * use either a whitelist ($wgProfiler['include']) or a blacklist
+ * ($wgProfiler['exclude']) containing an array of function names.
+ * Shell-style patterns are also accepted.
+ *
+ * It is also possible to use the Tideways PHP extension, which is mostly
+ * a drop-in replacement for Xhprof. Just change the XHPROF_FLAGS_* constants
+ * to TIDEWAYS_FLAGS_*.
+ *
+ * @copyright © 2014 Wikimedia Foundation and contributors
+ * @ingroup Profiler
+ * @see Xhprof
+ * @see https://php.net/xhprof
+ * @see https://github.com/facebook/hhvm/blob/master/hphp/doc/profiling.md
+ * @see https://github.com/tideways/php-profiler-extension
+ */
+class ProfilerXhprof extends Profiler {
+ /**
+ * @var XhprofData|null $xhprofData
+ */
+ protected $xhprofData;
+
+ /**
+ * Profiler for explicit, arbitrary, frame labels
+ * @var SectionProfiler
+ */
+ protected $sprofiler;
+
+ /**
+ * @param array $params
+ * @see Xhprof::__construct()
+ */
+ public function __construct( array $params = [] ) {
+ parent::__construct( $params );
+
+ $flags = isset( $params['flags'] ) ? $params['flags'] : 0;
+ $options = isset( $params['exclude'] )
+ ? [ 'ignored_functions' => $params['exclude'] ] : [];
+ Xhprof::enable( $flags, $options );
+ $this->sprofiler = new SectionProfiler();
+ }
+
+ /**
+ * @return XhprofData
+ */
+ public function getXhprofData() {
+ if ( !$this->xhprofData ) {
+ $this->xhprofData = new XhprofData( Xhprof::disable(), $this->params );
+ }
+ return $this->xhprofData;
+ }
+
+ public function scopedProfileIn( $section ) {
+ $key = 'section.' . ltrim( $section, '.' );
+ return $this->sprofiler->scopedProfileIn( $key );
+ }
+
+ /**
+ * No-op for xhprof profiling.
+ */
+ public function close() {
+ }
+
+ /**
+ * Check if a function or section should be excluded from the output.
+ *
+ * @param string $name Function or section name.
+ * @return bool
+ */
+ private function shouldExclude( $name ) {
+ if ( $name === '-total' ) {
+ return true;
+ }
+ if ( !empty( $this->params['include'] ) ) {
+ foreach ( $this->params['include'] as $pattern ) {
+ if ( fnmatch( $pattern, $name, FNM_NOESCAPE ) ) {
+ return false;
+ }
+ }
+ return true;
+ }
+ if ( !empty( $this->params['exclude'] ) ) {
+ foreach ( $this->params['exclude'] as $pattern ) {
+ if ( fnmatch( $pattern, $name, FNM_NOESCAPE ) ) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ public function getFunctionStats() {
+ $metrics = $this->getXhprofData()->getCompleteMetrics();
+ $profile = [];
+
+ $main = null; // units in ms
+ foreach ( $metrics as $fname => $stats ) {
+ if ( $this->shouldExclude( $fname ) ) {
+ continue;
+ }
+ // Convert elapsed times from μs to ms to match interface
+ $entry = [
+ 'name' => $fname,
+ 'calls' => $stats['ct'],
+ 'real' => $stats['wt']['total'] / 1000,
+ '%real' => $stats['wt']['percent'],
+ 'cpu' => isset( $stats['cpu'] ) ? $stats['cpu']['total'] / 1000 : 0,
+ '%cpu' => isset( $stats['cpu'] ) ? $stats['cpu']['percent'] : 0,
+ 'memory' => isset( $stats['mu'] ) ? $stats['mu']['total'] : 0,
+ '%memory' => isset( $stats['mu'] ) ? $stats['mu']['percent'] : 0,
+ 'min_real' => $stats['wt']['min'] / 1000,
+ 'max_real' => $stats['wt']['max'] / 1000
+ ];
+ $profile[] = $entry;
+ if ( $fname === 'main()' ) {
+ $main = $entry;
+ }
+ }
+
+ // Merge in all of the custom profile sections
+ foreach ( $this->sprofiler->getFunctionStats() as $stats ) {
+ if ( $this->shouldExclude( $stats['name'] ) ) {
+ continue;
+ }
+
+ // @note: getFunctionStats() values already in ms
+ $stats['%real'] = $main['real'] ? $stats['real'] / $main['real'] * 100 : 0;
+ $stats['%cpu'] = $main['cpu'] ? $stats['cpu'] / $main['cpu'] * 100 : 0;
+ $stats['%memory'] = $main['memory'] ? $stats['memory'] / $main['memory'] * 100 : 0;
+ $profile[] = $stats; // assume no section names collide with $metrics
+ }
+
+ return $profile;
+ }
+
+ /**
+ * Returns a profiling output to be stored in debug file
+ *
+ * @return string
+ */
+ public function getOutput() {
+ return $this->getFunctionReport();
+ }
+
+ /**
+ * Get a report of profiled functions sorted by inclusive wall clock time
+ * in descending order.
+ *
+ * Each line of the report includes this data:
+ * - Function name
+ * - Number of times function was called
+ * - Total wall clock time spent in function in microseconds
+ * - Minimum wall clock time spent in function in microseconds
+ * - Average wall clock time spent in function in microseconds
+ * - Maximum wall clock time spent in function in microseconds
+ * - Percentage of total wall clock time spent in function
+ * - Total delta of memory usage from start to end of function in bytes
+ *
+ * @return string
+ */
+ protected function getFunctionReport() {
+ $data = $this->getFunctionStats();
+ usort( $data, function ( $a, $b ) {
+ if ( $a['real'] === $b['real'] ) {
+ return 0;
+ }
+ return ( $a['real'] > $b['real'] ) ? -1 : 1; // descending
+ } );
+
+ $width = 140;
+ $nameWidth = $width - 65;
+ $format = "%-{$nameWidth}s %6d %9d %9d %9d %9d %7.3f%% %9d";
+ $out = [];
+ $out[] = sprintf( "%-{$nameWidth}s %6s %9s %9s %9s %9s %7s %9s",
+ 'Name', 'Calls', 'Total', 'Min', 'Each', 'Max', '%', 'Mem'
+ );
+ foreach ( $data as $stats ) {
+ $out[] = sprintf( $format,
+ $stats['name'],
+ $stats['calls'],
+ $stats['real'] * 1000,
+ $stats['min_real'] * 1000,
+ $stats['real'] / $stats['calls'] * 1000,
+ $stats['max_real'] * 1000,
+ $stats['%real'],
+ $stats['memory']
+ );
+ }
+ return implode( "\n", $out );
+ }
+
+ /**
+ * Retrieve raw data from xhprof
+ * @return array
+ */
+ public function getRawData() {
+ return $this->getXhprofData()->getRawData();
+ }
+}
diff --git a/www/wiki/includes/profiler/SectionProfiler.php b/www/wiki/includes/profiler/SectionProfiler.php
new file mode 100644
index 00000000..57bd01f8
--- /dev/null
+++ b/www/wiki/includes/profiler/SectionProfiler.php
@@ -0,0 +1,524 @@
+<?php
+/**
+ * Arbitrary section name based PHP profiling.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ *
+ * @file
+ * @ingroup Profiler
+ */
+use Wikimedia\ScopedCallback;
+
+/**
+ * Custom PHP profiler for parser/DB type section names that xhprof/xdebug can't handle
+ *
+ * @since 1.25
+ */
+class SectionProfiler {
+ /** @var array Map of (mem,real,cpu) */
+ protected $start;
+ /** @var array Map of (mem,real,cpu) */
+ protected $end;
+ /** @var array List of resolved profile calls with start/end data */
+ protected $stack = [];
+ /** @var array Queue of open profile calls with start data */
+ protected $workStack = [];
+
+ /** @var array Map of (function name => aggregate data array) */
+ protected $collated = [];
+ /** @var bool */
+ protected $collateDone = false;
+
+ /** @var bool Whether to collect the full stack trace or just aggregates */
+ protected $collateOnly = true;
+ /** @var array Cache of a standard broken collation entry */
+ protected $errorEntry;
+
+ /**
+ * @param array $params
+ */
+ public function __construct( array $params = [] ) {
+ $this->errorEntry = $this->getErrorEntry();
+ $this->collateOnly = empty( $params['trace'] );
+ }
+
+ /**
+ * @param string $section
+ * @return SectionProfileCallback
+ */
+ public function scopedProfileIn( $section ) {
+ $this->profileInInternal( $section );
+
+ return new SectionProfileCallback( $this, $section );
+ }
+
+ /**
+ * @param ScopedCallback &$section
+ */
+ public function scopedProfileOut( ScopedCallback &$section ) {
+ $section = null;
+ }
+
+ /**
+ * Get the aggregated inclusive profiling data for each method
+ *
+ * The percent time for each time is based on the current "total" time
+ * used is based on all methods so far. This method can therefore be
+ * called several times in between several profiling calls without the
+ * delays in usage of the profiler skewing the results. A "-total" entry
+ * is always included in the results.
+ *
+ * @return array List of method entries arrays, each having:
+ * - name : method name
+ * - calls : the number of invoking calls
+ * - real : real time elapsed (ms)
+ * - %real : percent real time
+ * - cpu : real time elapsed (ms)
+ * - %cpu : percent real time
+ * - memory : memory used (bytes)
+ * - %memory : percent memory used
+ * - min_real : min real time in a call (ms)
+ * - max_real : max real time in a call (ms)
+ */
+ public function getFunctionStats() {
+ $this->collateData();
+
+ $totalCpu = max( $this->end['cpu'] - $this->start['cpu'], 0 );
+ $totalReal = max( $this->end['real'] - $this->start['real'], 0 );
+ $totalMem = max( $this->end['memory'] - $this->start['memory'], 0 );
+
+ $profile = [];
+ foreach ( $this->collated as $fname => $data ) {
+ $profile[] = [
+ 'name' => $fname,
+ 'calls' => $data['count'],
+ 'real' => $data['real'] * 1000,
+ '%real' => $totalReal ? 100 * $data['real'] / $totalReal : 0,
+ 'cpu' => $data['cpu'] * 1000,
+ '%cpu' => $totalCpu ? 100 * $data['cpu'] / $totalCpu : 0,
+ 'memory' => $data['memory'],
+ '%memory' => $totalMem ? 100 * $data['memory'] / $totalMem : 0,
+ 'min_real' => 1000 * $data['min_real'],
+ 'max_real' => 1000 * $data['max_real']
+ ];
+ }
+
+ $profile[] = [
+ 'name' => '-total',
+ 'calls' => 1,
+ 'real' => 1000 * $totalReal,
+ '%real' => 100,
+ 'cpu' => 1000 * $totalCpu,
+ '%cpu' => 100,
+ 'memory' => $totalMem,
+ '%memory' => 100,
+ 'min_real' => 1000 * $totalReal,
+ 'max_real' => 1000 * $totalReal
+ ];
+
+ return $profile;
+ }
+
+ /**
+ * Clear all of the profiling data for another run
+ */
+ public function reset() {
+ $this->start = null;
+ $this->end = null;
+ $this->stack = [];
+ $this->workStack = [];
+ $this->collated = [];
+ $this->collateDone = false;
+ }
+
+ /**
+ * @return array Initial collation entry
+ */
+ protected function getZeroEntry() {
+ return [
+ 'cpu' => 0.0,
+ 'real' => 0.0,
+ 'memory' => 0,
+ 'count' => 0,
+ 'min_real' => 0.0,
+ 'max_real' => 0.0
+ ];
+ }
+
+ /**
+ * @return array Initial collation entry for errors
+ */
+ protected function getErrorEntry() {
+ $entry = $this->getZeroEntry();
+ $entry['count'] = 1;
+ return $entry;
+ }
+
+ /**
+ * Update the collation entry for a given method name
+ *
+ * @param string $name
+ * @param float $elapsedCpu
+ * @param float $elapsedReal
+ * @param int $memChange
+ */
+ protected function updateEntry( $name, $elapsedCpu, $elapsedReal, $memChange ) {
+ $entry =& $this->collated[$name];
+ if ( !is_array( $entry ) ) {
+ $entry = $this->getZeroEntry();
+ $this->collated[$name] =& $entry;
+ }
+ $entry['cpu'] += $elapsedCpu;
+ $entry['real'] += $elapsedReal;
+ $entry['memory'] += $memChange > 0 ? $memChange : 0;
+ $entry['count']++;
+ $entry['min_real'] = min( $entry['min_real'], $elapsedReal );
+ $entry['max_real'] = max( $entry['max_real'], $elapsedReal );
+ }
+
+ /**
+ * This method should not be called outside SectionProfiler
+ *
+ * @param string $functionname
+ */
+ public function profileInInternal( $functionname ) {
+ // Once the data is collated for reports, any future calls
+ // should clear the collation cache so the next report will
+ // reflect them. This matters when trace mode is used.
+ $this->collateDone = false;
+
+ $cpu = $this->getTime( 'cpu' );
+ $real = $this->getTime( 'wall' );
+ $memory = memory_get_usage();
+
+ if ( $this->start === null ) {
+ $this->start = [ 'cpu' => $cpu, 'real' => $real, 'memory' => $memory ];
+ }
+
+ $this->workStack[] = [
+ $functionname,
+ count( $this->workStack ),
+ $real,
+ $cpu,
+ $memory
+ ];
+ }
+
+ /**
+ * This method should not be called outside SectionProfiler
+ *
+ * @param string $functionname
+ */
+ public function profileOutInternal( $functionname ) {
+ $item = array_pop( $this->workStack );
+ if ( $item === null ) {
+ $this->debugGroup( 'profileerror', "Profiling error: $functionname" );
+ return;
+ }
+ list( $ofname, /* $ocount */, $ortime, $octime, $omem ) = $item;
+
+ if ( $functionname === 'close' ) {
+ $message = "Profile section ended by close(): {$ofname}";
+ $this->debugGroup( 'profileerror', $message );
+ if ( $this->collateOnly ) {
+ $this->collated[$message] = $this->errorEntry;
+ } else {
+ $this->stack[] = [ $message, 0, 0.0, 0.0, 0, 0.0, 0.0, 0 ];
+ }
+ $functionname = $ofname;
+ } elseif ( $ofname !== $functionname ) {
+ $message = "Profiling error: in({$ofname}), out($functionname)";
+ $this->debugGroup( 'profileerror', $message );
+ if ( $this->collateOnly ) {
+ $this->collated[$message] = $this->errorEntry;
+ } else {
+ $this->stack[] = [ $message, 0, 0.0, 0.0, 0, 0.0, 0.0, 0 ];
+ }
+ }
+
+ $realTime = $this->getTime( 'wall' );
+ $cpuTime = $this->getTime( 'cpu' );
+ $memUsage = memory_get_usage();
+
+ if ( $this->collateOnly ) {
+ $elapsedcpu = $cpuTime - $octime;
+ $elapsedreal = $realTime - $ortime;
+ $memchange = $memUsage - $omem;
+ $this->updateEntry( $functionname, $elapsedcpu, $elapsedreal, $memchange );
+ } else {
+ $this->stack[] = array_merge( $item, [ $realTime, $cpuTime, $memUsage ] );
+ }
+
+ $this->end = [
+ 'cpu' => $cpuTime,
+ 'real' => $realTime,
+ 'memory' => $memUsage
+ ];
+ }
+
+ /**
+ * Returns a tree of function calls with their real times
+ * @return string
+ * @throws Exception
+ */
+ public function getCallTreeReport() {
+ if ( $this->collateOnly ) {
+ throw new Exception( "Tree is only available for trace profiling." );
+ }
+ return implode( '', array_map(
+ [ $this, 'getCallTreeLine' ], $this->remapCallTree( $this->stack )
+ ) );
+ }
+
+ /**
+ * Recursive function the format the current profiling array into a tree
+ *
+ * @param array $stack Profiling array
+ * @return array
+ */
+ protected function remapCallTree( array $stack ) {
+ if ( count( $stack ) < 2 ) {
+ return $stack;
+ }
+ $outputs = [];
+ for ( $max = count( $stack ) - 1; $max > 0; ) {
+ /* Find all items under this entry */
+ $level = $stack[$max][1];
+ $working = [];
+ for ( $i = $max - 1; $i >= 0; $i-- ) {
+ if ( $stack[$i][1] > $level ) {
+ $working[] = $stack[$i];
+ } else {
+ break;
+ }
+ }
+ $working = $this->remapCallTree( array_reverse( $working ) );
+ $output = [];
+ foreach ( $working as $item ) {
+ array_push( $output, $item );
+ }
+ array_unshift( $output, $stack[$max] );
+ $max = $i;
+
+ array_unshift( $outputs, $output );
+ }
+ $final = [];
+ foreach ( $outputs as $output ) {
+ foreach ( $output as $item ) {
+ $final[] = $item;
+ }
+ }
+ return $final;
+ }
+
+ /**
+ * Callback to get a formatted line for the call tree
+ * @param array $entry
+ * @return string
+ */
+ protected function getCallTreeLine( $entry ) {
+ // $entry has (name, level, stime, scpu, smem, etime, ecpu, emem)
+ list( $fname, $level, $startreal, , , $endreal ) = $entry;
+ $delta = $endreal - $startreal;
+ $space = str_repeat( ' ', $level );
+ # The ugly double sprintf is to work around a PHP bug,
+ # which has been fixed in recent releases.
+ return sprintf( "%10s %s %s\n",
+ trim( sprintf( "%7.3f", $delta * 1000.0 ) ), $space, $fname );
+ }
+
+ /**
+ * Populate collated data
+ */
+ protected function collateData() {
+ if ( $this->collateDone ) {
+ return;
+ }
+ $this->collateDone = true;
+ // Close opened profiling sections
+ while ( count( $this->workStack ) ) {
+ $this->profileOutInternal( 'close' );
+ }
+
+ if ( $this->collateOnly ) {
+ return; // already collated as methods exited
+ }
+
+ $this->collated = [];
+
+ # Estimate profiling overhead
+ $oldEnd = $this->end;
+ $profileCount = count( $this->stack );
+ $this->calculateOverhead( $profileCount );
+
+ # First, subtract the overhead!
+ $overheadTotal = $overheadMemory = $overheadInternal = [];
+ foreach ( $this->stack as $entry ) {
+ // $entry is (name,pos,rtime0,cputime0,mem0,rtime1,cputime1,mem1)
+ $fname = $entry[0];
+ $elapsed = $entry[5] - $entry[2];
+ $memchange = $entry[7] - $entry[4];
+
+ if ( $fname === '-overhead-total' ) {
+ $overheadTotal[] = $elapsed;
+ $overheadMemory[] = max( 0, $memchange );
+ } elseif ( $fname === '-overhead-internal' ) {
+ $overheadInternal[] = $elapsed;
+ }
+ }
+ $overheadTotal = $overheadTotal ?
+ array_sum( $overheadTotal ) / count( $overheadInternal ) : 0;
+ $overheadMemory = $overheadMemory ?
+ array_sum( $overheadMemory ) / count( $overheadInternal ) : 0;
+ $overheadInternal = $overheadInternal ?
+ array_sum( $overheadInternal ) / count( $overheadInternal ) : 0;
+
+ # Collate
+ foreach ( $this->stack as $index => $entry ) {
+ // $entry is (name,pos,rtime0,cputime0,mem0,rtime1,cputime1,mem1)
+ $fname = $entry[0];
+ $elapsedCpu = $entry[6] - $entry[3];
+ $elapsedReal = $entry[5] - $entry[2];
+ $memchange = $entry[7] - $entry[4];
+ $subcalls = $this->calltreeCount( $this->stack, $index );
+
+ if ( substr( $fname, 0, 9 ) !== '-overhead' ) {
+ # Adjust for profiling overhead (except special values with elapsed=0)
+ if ( $elapsed ) {
+ $elapsed -= $overheadInternal;
+ $elapsed -= ( $subcalls * $overheadTotal );
+ $memchange -= ( $subcalls * $overheadMemory );
+ }
+ }
+
+ $this->updateEntry( $fname, $elapsedCpu, $elapsedReal, $memchange );
+ }
+
+ $this->collated['-overhead-total']['count'] = $profileCount;
+ arsort( $this->collated, SORT_NUMERIC );
+
+ // Unclobber the end info map (the overhead checking alters it)
+ $this->end = $oldEnd;
+ }
+
+ /**
+ * Dummy calls to calculate profiling overhead
+ *
+ * @param int $profileCount
+ */
+ protected function calculateOverhead( $profileCount ) {
+ $this->profileInInternal( '-overhead-total' );
+ for ( $i = 0; $i < $profileCount; $i++ ) {
+ $this->profileInInternal( '-overhead-internal' );
+ $this->profileOutInternal( '-overhead-internal' );
+ }
+ $this->profileOutInternal( '-overhead-total' );
+ }
+
+ /**
+ * Counts the number of profiled function calls sitting under
+ * the given point in the call graph. Not the most efficient algo.
+ *
+ * @param array $stack
+ * @param int $start
+ * @return int
+ */
+ protected function calltreeCount( $stack, $start ) {
+ $level = $stack[$start][1];
+ $count = 0;
+ for ( $i = $start - 1; $i >= 0 && $stack[$i][1] > $level; $i-- ) {
+ $count ++;
+ }
+ return $count;
+ }
+
+ /**
+ * Get the initial time of the request, based on getrusage()
+ *
+ * @param string|bool $metric Metric to use, with the following possibilities:
+ * - user: User CPU time (without system calls)
+ * - cpu: Total CPU time (user and system calls)
+ * - wall (or any other string): elapsed time
+ * - false (default): will fall back to default metric
+ * @return float
+ */
+ protected function getTime( $metric = 'wall' ) {
+ if ( $metric === 'cpu' || $metric === 'user' ) {
+ $ru = wfGetRusage();
+ if ( !$ru ) {
+ return 0;
+ }
+ $time = $ru['ru_utime.tv_sec'] + $ru['ru_utime.tv_usec'] / 1e6;
+ if ( $metric === 'cpu' ) {
+ # This is the time of system calls, added to the user time
+ # it gives the total CPU time
+ $time += $ru['ru_stime.tv_sec'] + $ru['ru_stime.tv_usec'] / 1e6;
+ }
+ return $time;
+ } else {
+ return microtime( true );
+ }
+ }
+
+ /**
+ * Add an entry in the debug log file
+ *
+ * @param string $s String to output
+ */
+ protected function debug( $s ) {
+ if ( function_exists( 'wfDebug' ) ) {
+ wfDebug( $s );
+ }
+ }
+
+ /**
+ * Add an entry in the debug log group
+ *
+ * @param string $group Group to send the message to
+ * @param string $s String to output
+ */
+ protected function debugGroup( $group, $s ) {
+ if ( function_exists( 'wfDebugLog' ) ) {
+ wfDebugLog( $group, $s );
+ }
+ }
+}
+
+/**
+ * Subclass ScopedCallback to avoid call_user_func_array(), which is slow
+ *
+ * This class should not be used outside of SectionProfiler
+ */
+class SectionProfileCallback extends ScopedCallback {
+ /** @var SectionProfiler */
+ protected $profiler;
+ /** @var string */
+ protected $section;
+
+ /**
+ * @param SectionProfiler $profiler
+ * @param string $section
+ */
+ public function __construct( SectionProfiler $profiler, $section ) {
+ parent::__construct( null );
+ $this->profiler = $profiler;
+ $this->section = $section;
+ }
+
+ function __destruct() {
+ $this->profiler->profileOutInternal( $this->section );
+ }
+}
diff --git a/www/wiki/includes/profiler/output/ProfilerOutput.php b/www/wiki/includes/profiler/output/ProfilerOutput.php
new file mode 100644
index 00000000..20b07801
--- /dev/null
+++ b/www/wiki/includes/profiler/output/ProfilerOutput.php
@@ -0,0 +1,56 @@
+<?php
+/**
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ *
+ * @file
+ * @ingroup Profiler
+ */
+
+/**
+ * Base class for profiling output
+ *
+ * Since 1.25
+ */
+abstract class ProfilerOutput {
+ /** @var Profiler */
+ protected $collector;
+ /** @var array Configuration of $wgProfiler */
+ protected $params = [];
+
+ /**
+ * @param Profiler $collector The actual profiler
+ * @param array $params Configuration array, passed down from $wgProfiler
+ */
+ public function __construct( Profiler $collector, array $params ) {
+ $this->collector = $collector;
+ $this->params = $params;
+ }
+
+ /**
+ * Can this output type be used?
+ * @return bool
+ */
+ public function canUse() {
+ return true;
+ }
+
+ /**
+ * Log MediaWiki-style profiling data
+ *
+ * @param array $stats Result of Profiler::getFunctionStats()
+ */
+ abstract public function log( array $stats );
+}
diff --git a/www/wiki/includes/profiler/output/ProfilerOutputDb.php b/www/wiki/includes/profiler/output/ProfilerOutputDb.php
new file mode 100644
index 00000000..28dc2cc2
--- /dev/null
+++ b/www/wiki/includes/profiler/output/ProfilerOutputDb.php
@@ -0,0 +1,106 @@
+<?php
+/**
+ * Profiler storing information in the DB.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ *
+ * @file
+ * @ingroup Profiler
+ */
+
+use Wikimedia\Rdbms\DBError;
+
+/**
+ * Logs profiling data into the local DB
+ *
+ * @ingroup Profiler
+ * @since 1.25
+ */
+class ProfilerOutputDb extends ProfilerOutput {
+ /** @var bool Whether to store host data with profiling calls */
+ private $perHost = false;
+
+ public function __construct( Profiler $collector, array $params ) {
+ parent::__construct( $collector, $params );
+
+ // Initialize per-host profiling from config, back-compat if available
+ if ( isset( $this->params['perHost'] ) ) {
+ $this->perHost = $this->params['perHost'];
+ }
+ }
+
+ public function canUse() {
+ # Do not log anything if database is readonly (T7375)
+ return !wfReadOnly();
+ }
+
+ public function log( array $stats ) {
+ try {
+ $dbw = wfGetDB( DB_MASTER );
+ } catch ( DBError $e ) {
+ return; // ignore
+ }
+
+ $fname = __METHOD__;
+ $dbw->onTransactionIdle( function () use ( $stats, $dbw, $fname ) {
+ $pfhost = $this->perHost ? wfHostname() : '';
+ // Sqlite: avoid excess b-tree rebuilds (mostly for non-WAL mode)
+ // non-Sqlite: lower contention with small transactions
+ $useTrx = ( $dbw->getType() === 'sqlite' );
+
+ try {
+ $useTrx ? $dbw->startAtomic( $fname ) : null;
+
+ foreach ( $stats as $data ) {
+ $name = $data['name'];
+ $eventCount = $data['calls'];
+ $timeSum = (float)$data['real'];
+ $memorySum = (float)$data['memory'];
+ $name = substr( $name, 0, 255 );
+
+ // Kludge
+ $timeSum = $timeSum >= 0 ? $timeSum : 0;
+ $memorySum = $memorySum >= 0 ? $memorySum : 0;
+
+ $dbw->upsert( 'profiling',
+ [
+ 'pf_name' => $name,
+ 'pf_count' => $eventCount,
+ 'pf_time' => $timeSum,
+ 'pf_memory' => $memorySum,
+ 'pf_server' => $pfhost
+ ],
+ [ [ 'pf_name', 'pf_server' ] ],
+ [
+ "pf_count=pf_count+{$eventCount}",
+ "pf_time=pf_time+{$timeSum}",
+ "pf_memory=pf_memory+{$memorySum}",
+ ],
+ $fname
+ );
+ }
+ } catch ( DBError $e ) {
+ // ignore
+ }
+
+ try {
+ $useTrx ? $dbw->endAtomic( $fname ) : null;
+ } catch ( DBError $e ) {
+ // ignore
+ }
+ } );
+ }
+}
diff --git a/www/wiki/includes/profiler/output/ProfilerOutputDump.php b/www/wiki/includes/profiler/output/ProfilerOutputDump.php
new file mode 100644
index 00000000..09f56887
--- /dev/null
+++ b/www/wiki/includes/profiler/output/ProfilerOutputDump.php
@@ -0,0 +1,55 @@
+<?php
+/**
+ * Profiler dumping output in xhprof dump file
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ *
+ * @file
+ * @ingroup Profiler
+ */
+
+/**
+ * Profiler dumping output in xhprof dump file
+ * @ingroup Profiler
+ *
+ * @since 1.25
+ */
+class ProfilerOutputDump extends ProfilerOutput {
+
+ protected $suffix = ".xhprof";
+
+ /**
+ * Can this output type be used?
+ *
+ * @return bool
+ */
+ public function canUse() {
+ if ( empty( $this->params['outputDir'] ) ) {
+ return false;
+ }
+ return true;
+ }
+
+ public function log( array $stats ) {
+ $data = $this->collector->getRawData();
+ $filename = sprintf( "%s/%s.%s%s",
+ $this->params['outputDir'],
+ uniqid(),
+ $this->collector->getProfileID(),
+ $this->suffix );
+ file_put_contents( $filename, serialize( $data ) );
+ }
+}
diff --git a/www/wiki/includes/profiler/output/ProfilerOutputStats.php b/www/wiki/includes/profiler/output/ProfilerOutputStats.php
new file mode 100644
index 00000000..bb865518
--- /dev/null
+++ b/www/wiki/includes/profiler/output/ProfilerOutputStats.php
@@ -0,0 +1,56 @@
+<?php
+/**
+ * ProfilerOutput class that flushes profiling data to the profiling
+ * context's stats buffer.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ *
+ * @file
+ * @ingroup Profiler
+ */
+use MediaWiki\MediaWikiServices;
+
+/**
+ * ProfilerOutput class that flushes profiling data to the profiling
+ * context's stats buffer.
+ *
+ * @ingroup Profiler
+ * @since 1.25
+ */
+class ProfilerOutputStats extends ProfilerOutput {
+
+ /**
+ * Flush profiling data to the current profiling context's stats buffer.
+ *
+ * @param array $stats
+ */
+ public function log( array $stats ) {
+ $prefix = isset( $this->params['prefix'] ) ? $this->params['prefix'] : '';
+ $contextStats = MediaWikiServices::getInstance()->getStatsdDataFactory();
+
+ foreach ( $stats as $stat ) {
+ $key = "{$prefix}.{$stat['name']}";
+
+ // Convert fractional seconds to whole milliseconds
+ $cpu = round( $stat['cpu'] * 1000 );
+ $real = round( $stat['real'] * 1000 );
+
+ $contextStats->increment( "{$key}.calls" );
+ $contextStats->timing( "{$key}.cpu", $cpu );
+ $contextStats->timing( "{$key}.real", $real );
+ }
+ }
+}
diff --git a/www/wiki/includes/profiler/output/ProfilerOutputText.php b/www/wiki/includes/profiler/output/ProfilerOutputText.php
new file mode 100644
index 00000000..100304ff
--- /dev/null
+++ b/www/wiki/includes/profiler/output/ProfilerOutputText.php
@@ -0,0 +1,77 @@
+<?php
+/**
+ * Profiler showing output in page source.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ *
+ * @file
+ * @ingroup Profiler
+ */
+
+/**
+ * The least sophisticated profiler output class possible, view your source! :)
+ *
+ * @ingroup Profiler
+ * @since 1.25
+ */
+class ProfilerOutputText extends ProfilerOutput {
+ /** @var float Min real time display threshold */
+ protected $thresholdMs;
+
+ function __construct( Profiler $collector, array $params ) {
+ parent::__construct( $collector, $params );
+ $this->thresholdMs = isset( $params['thresholdMs'] )
+ ? $params['thresholdMs']
+ : 1.0;
+ }
+ public function log( array $stats ) {
+ if ( $this->collector->getTemplated() ) {
+ $out = '';
+
+ // Filter out really tiny entries
+ $min = $this->thresholdMs;
+ $stats = array_filter( $stats, function ( $a ) use ( $min ) {
+ return $a['real'] > $min;
+ } );
+ // Sort descending by time elapsed
+ usort( $stats, function ( $a, $b ) {
+ return $a['real'] < $b['real'];
+ } );
+
+ array_walk( $stats,
+ function ( $item ) use ( &$out ) {
+ $out .= sprintf( "%6.2f%% %3.3f %6d - %s\n",
+ $item['%real'], $item['real'], $item['calls'], $item['name'] );
+ }
+ );
+
+ $contentType = $this->collector->getContentType();
+ if ( wfIsCLI() ) {
+ print "<!--\n{$out}\n-->\n";
+ } elseif ( $contentType === 'text/html' ) {
+ $visible = isset( $this->params['visible'] ) ?
+ $this->params['visible'] : false;
+ if ( $visible ) {
+ print "<pre>{$out}</pre>";
+ } else {
+ print "<!--\n{$out}\n-->\n";
+ }
+ } elseif ( $contentType === 'text/javascript' || $contentType === 'text/css' ) {
+ print "\n/*\n{$out}*/\n";
+ }
+ }
+ }
+}