Merge "Don't check namespace in SpecialWantedtemplates"
[lhc/web/wiklou.git] / includes / profiler / SectionProfiler.php
index 89eebbe..63940bc 100644 (file)
  * @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 = array();
        /** @var array Queue of open profile calls with start data */
@@ -37,11 +41,13 @@ class SectionProfiler {
        protected $collated = array();
        /** @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;
+       /** @var callable Cache of a profile out callback */
+       protected $profileOutCallback;
 
        /**
         * @param array $params
@@ -49,6 +55,9 @@ class SectionProfiler {
        public function __construct( array $params = array() ) {
                $this->errorEntry = $this->getErrorEntry();
                $this->collateOnly = empty( $params['trace'] );
+               $this->profileOutCallback = function ( $profiler, $section ) {
+                       $profiler->profileOutInternal( $section );
+               };
        }
 
        /**
@@ -58,10 +67,7 @@ class SectionProfiler {
        public function scopedProfileIn( $section ) {
                $this->profileInInternal( $section );
 
-               $that = $this;
-               return new ScopedCallback( function() use ( $that, $section ) {
-                       $that->profileOutInternal( $section );
-               } );
+               return new SectionProfileCallback( $this, $section );
        }
 
        /**
@@ -83,24 +89,21 @@ class SectionProfiler {
         * @return array List of method entries arrays, each having:
         *   - name    : method name
         *   - calls   : the number of invoking calls
-        *   - real    : real time ellapsed (ms)
+        *   - real    : real time elapsed (ms)
         *   - %real   : percent real time
-        *   - cpu     : real time ellapsed (ms)
+        *   - 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 = 0.0;
-               $totalReal = 0.0;
-               $totalMem = 0;
-               foreach ( $this->collated as $fname => $data ) {
-                       $totalCpu += $data['cpu'];
-                       $totalReal += $data['real'];
-                       $totalMem += $data['memory'];
-               }
+               $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 = array();
                foreach ( $this->collated as $fname => $data ) {
@@ -113,6 +116,8 @@ class SectionProfiler {
                                '%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']
                        );
                }
 
@@ -125,11 +130,25 @@ class SectionProfiler {
                        '%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 = array();
+               $this->workStack = array();
+               $this->collated = array();
+               $this->collateDone = false;
+       }
+
        /**
         * @return array Initial collation entry
         */
@@ -138,7 +157,9 @@ class SectionProfiler {
                        'cpu'      => 0.0,
                        'real'     => 0.0,
                        'memory'   => 0,
-                       'count'    => 0
+                       'count'    => 0,
+                       'min_real' => 0.0,
+                       'max_real' => 0.0
                );
        }
 
@@ -169,6 +190,8 @@ class SectionProfiler {
                $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 );
        }
 
        /**
@@ -177,12 +200,25 @@ class 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 = array( 'cpu' => $cpu, 'real' => $real, 'memory' => $memory );
+               }
+
                $this->workStack[] = array(
                        $functionname,
                        count( $this->workStack ),
-                       $this->getTime( 'time' ),
-                       $this->getTime( 'cpu' ),
-                       memory_get_usage()
+                       $real,
+                       $cpu,
+                       $memory
                );
        }
 
@@ -217,22 +253,31 @@ class SectionProfiler {
                                $this->stack[] = array( $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 = memory_get_usage() - $omem;
+                       $memchange = $memUsage - $omem;
                        $this->updateEntry( $functionname, $elapsedcpu, $elapsedreal, $memchange );
                } else {
-                       $this->stack[] = array_merge( $item,
-                               array( $realTime, $cpuTime,     memory_get_usage() ) );
+                       $this->stack[] = array_merge( $item, array( $realTime, $cpuTime, $memUsage ) );
                }
+
+               $this->end = array(
+                       '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 ) {
@@ -320,6 +365,7 @@ class SectionProfiler {
                $this->collated = array();
 
                # Estimate profiling overhead
+               $oldEnd = $this->end;
                $profileCount = count( $this->stack );
                $this->calculateOverhead( $profileCount );
 
@@ -355,7 +401,7 @@ class SectionProfiler {
                        $subcalls = $this->calltreeCount( $this->stack, $index );
 
                        if ( substr( $fname, 0, 9 ) !== '-overhead' ) {
-                               # Adjust for profiling overhead (except special values with elapsed=0
+                               # Adjust for profiling overhead (except special values with elapsed=0)
                                if ( $elapsed ) {
                                        $elapsed -= $overheadInternal;
                                        $elapsed -= ( $subcalls * $overheadTotal );
@@ -368,6 +414,9 @@ class SectionProfiler {
 
                $this->collated['-overhead-total']['count'] = $profileCount;
                arsort( $this->collated, SORT_NUMERIC );
+
+               // Unclobber the end info map (the overhead checking alters it)
+               $this->end = $oldEnd;
        }
 
        /**
@@ -402,15 +451,14 @@ class SectionProfiler {
        }
 
        /**
-        * Get the initial time of the request, based either on $wgRequestTime or
-        * $wgRUstart. Will return null if not able to find data.
+        * 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|null
+        * @return float
         */
        protected function getTime( $metric = 'wall' ) {
                if ( $metric === 'cpu' || $metric === 'user' ) {
@@ -453,3 +501,29 @@ class SectionProfiler {
                }
        }
 }
+
+/**
+ * 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 );
+       }
+}