* @todo document
*/
class Profiler {
- protected $mStack = array(), $mWorkStack = array(), $mCollated = array(),
- $mCalls = array(), $mTotals = array(), $mPeriods = array();
+ /** @var array List of resolved profile calls with start/end data */
+ protected $mStack = array();
+ /** @var array Queue of open profile calls with start data */
+ protected $mWorkStack = array();
+
+ /** @var array Map of (function name => aggregate data array) */
+ protected $mCollated = array();
+ /** @var bool */
+ protected $mCollateDone = false;
+ /** @var bool */
+ protected $mCollateOnly = false;
+ /** @var array Cache of a standard broken collation entry */
+ protected $mErrorEntry;
+
+ /** @var string wall|cpu|user */
protected $mTimeMetric = 'wall';
- protected $mProfileID = false, $mCollateDone = false, $mTemplated = false;
+ /** @var string|bool Profiler ID for bucketing data */
+ protected $mProfileID = false;
+ /** @var bool Whether MediaWiki is in a SkinTemplate output context */
+ protected $mTemplated = false;
- protected $mDBLockThreshold = 5.0; // float; seconds
+ /** @var float seconds */
+ protected $mDBLockThreshold = 5.0;
/** @var Array DB/server name => (active trx count,timestamp) */
protected $mDBTrxHoldingLocks = array();
- /** @var Array DB/server name => list of (method, elapsed time) */
+ /** @var Array DB/server name => list of (function name, elapsed time) */
protected $mDBTrxMethodTimes = array();
/** @var Profiler */
public static $__instance = null; // do not call this outside Profiler and ProfileSection
- function __construct( $params ) {
+ /**
+ * @param array $params
+ */
+ public function __construct( array $params ) {
if ( isset( $params['timeMetric'] ) ) {
$this->mTimeMetric = $params['timeMetric'];
}
$this->mProfileID = $params['profileID'];
}
+ $this->mCollateOnly = $this->collateOnly();
+
$this->addInitialStack();
}
* @return Boolean
*/
public function isPersistent() {
- return true;
+ return false;
}
+ /**
+ * @param string $id
+ */
public function setProfileID( $id ) {
$this->mProfileID = $id;
}
+ /**
+ * @return string
+ */
public function getProfileID() {
if ( $this->mProfileID === false ) {
return wfWikiID();
}
}
+ /**
+ * Whether to internally just track aggregates and ignore the full stack trace
+ *
+ * @return boolean
+ */
+ protected function collateOnly() {
+ return false;
+ }
+
/**
* Add the inital item in the stack.
*/
protected function addInitialStack() {
- // Push an entry for the pre-profile setup time onto the stack
- $initial = $this->getInitialTime();
- if ( $initial !== null ) {
- $this->mWorkStack[] = array( '-total', 0, $initial, 0 );
- $this->mStack[] = array( '-setup', 1, $initial, 0, $this->getTime(), 0 );
+ $this->mErrorEntry = $this->getErrorEntry();
+
+ $initialTime = $this->getInitialTime( 'wall' );
+ $initialCpu = $this->getInitialTime( 'cpu' );
+ if ( $initialTime !== null && $initialCpu !== null ) {
+ $this->mWorkStack[] = array( '-total', 0, $initialTime, $initialCpu, 0 );
+ if ( $this->mCollateOnly ) {
+ $this->mWorkStack[] = array( '-setup', 1, $initialTime, $initialCpu, 0 );
+ $this->profileOut( '-setup' );
+ } else {
+ $this->mStack[] = array( '-setup', 1, $initialTime, $initialCpu, 0,
+ $this->getTime( 'wall' ), $this->getTime( 'cpu' ), 0 );
+ }
} else {
$this->profileIn( '-total' );
}
}
+ /**
+ * @return array Initial collation entry
+ */
+ protected function getZeroEntry() {
+ return array(
+ 'cpu' => 0.0,
+ 'cpu_sq' => 0.0,
+ 'real' => 0.0,
+ 'real_sq' => 0.0,
+ 'memory' => 0,
+ 'count' => 0,
+ 'min_cpu' => 0.0,
+ 'max_cpu' => 0.0,
+ 'min_real' => 0.0,
+ 'max_real' => 0.0,
+ 'periods' => array(), // not filled if mCollateOnly
+ 'overhead' => 0 // not filled if mCollateOnly
+ );
+ }
+
+ /**
+ * @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 integer $memChange
+ * @param integer $subcalls
+ * @param array|null $period Map of ('start','end','memory','subcalls')
+ */
+ protected function updateEntry(
+ $name, $elapsedCpu, $elapsedReal, $memChange, $subcalls = 0, $period = null
+ ) {
+ $entry =& $this->mCollated[$name];
+ if ( !is_array( $entry ) ) {
+ $entry = $this->getZeroEntry();
+ $this->mCollated[$name] =& $entry;
+ }
+ $entry['cpu'] += $elapsedCpu;
+ $entry['cpu_sq'] += $elapsedCpu * $elapsedCpu;
+ $entry['real'] += $elapsedReal;
+ $entry['real_sq'] += $elapsedReal * $elapsedReal;
+ $entry['memory'] += $memChange > 0 ? $memChange : 0;
+ $entry['count']++;
+ $entry['min_cpu'] = $elapsedCpu < $entry['min_cpu'] ? $elapsedCpu : $entry['min_cpu'];
+ $entry['max_cpu'] = $elapsedCpu > $entry['max_cpu'] ? $elapsedCpu : $entry['max_cpu'];
+ $entry['min_real'] = $elapsedReal < $entry['min_real'] ? $elapsedReal : $entry['min_real'];
+ $entry['max_real'] = $elapsedReal > $entry['max_real'] ? $elapsedReal : $entry['max_real'];
+ // Apply optional fields
+ $entry['overhead'] += $subcalls;
+ if ( $period ) {
+ $entry['periods'][] = $period;
+ }
+ }
+
/**
* Called by wfProfieIn()
*
*/
public function profileIn( $functionname ) {
global $wgDebugFunctionEntry;
+
if ( $wgDebugFunctionEntry ) {
- $this->debug( str_repeat( ' ', count( $this->mWorkStack ) ) . 'Entering ' . $functionname . "\n" );
+ $this->debug( str_repeat( ' ', count( $this->mWorkStack ) ) .
+ 'Entering ' . $functionname . "\n" );
}
- $this->mWorkStack[] = array( $functionname, count( $this->mWorkStack ), $this->getTime(), memory_get_usage() );
+ $this->mWorkStack[] = array(
+ $functionname,
+ count( $this->mWorkStack ),
+ $this->getTime( 'time' ),
+ $this->getTime( 'cpu' ),
+ memory_get_usage()
+ );
}
/**
*/
public function profileOut( $functionname ) {
global $wgDebugFunctionEntry;
- $memory = memory_get_usage();
- $time = $this->getTime();
if ( $wgDebugFunctionEntry ) {
- $this->debug( str_repeat( ' ', count( $this->mWorkStack ) - 1 ) . 'Exiting ' . $functionname . "\n" );
+ $this->debug( str_repeat( ' ', count( $this->mWorkStack ) - 1 ) .
+ 'Exiting ' . $functionname . "\n" );
}
- $bit = array_pop( $this->mWorkStack );
+ $item = array_pop( $this->mWorkStack );
+ list( $ofname, /* $ocount */, $ortime, $octime, $omem ) = $item;
- if ( !$bit ) {
- $this->debugGroup( 'profileerror', "Profiling error, !\$bit: $functionname" );
+ if ( $item === null ) {
+ $this->debugGroup( 'profileerror', "Profiling error: $functionname" );
} else {
- if ( $functionname == 'close' ) {
- if ( $bit[0] != '-total' ) {
- $message = "Profile section ended by close(): {$bit[0]}";
+ if ( $functionname === 'close' ) {
+ if ( $ofname !== '-total' ) {
+ $message = "Profile section ended by close(): {$ofname}";
$this->debugGroup( 'profileerror', $message );
- $this->mStack[] = array( $message, 0, 0.0, 0, 0.0, 0 );
+ if ( $this->mCollateOnly ) {
+ $this->mCollated[$message] = $this->mErrorEntry;
+ } else {
+ $this->mStack[] = array( $message, 0, 0.0, 0.0, 0, 0.0, 0.0, 0 );
+ }
}
- } elseif ( $bit[0] != $functionname ) {
- $message = "Profiling error: in({$bit[0]}), out($functionname)";
+ $functionname = $ofname;
+ } elseif ( $ofname !== $functionname ) {
+ $message = "Profiling error: in({$ofname}), out($functionname)";
$this->debugGroup( 'profileerror', $message );
- $this->mStack[] = array( $message, 0, 0.0, 0, 0.0, 0 );
+ if ( $this->mCollateOnly ) {
+ $this->mCollated[$message] = $this->mErrorEntry;
+ } else {
+ $this->mStack[] = array( $message, 0, 0.0, 0.0, 0, 0.0, 0.0, 0 );
+ }
+ }
+ $realTime = $this->getTime( 'wall' );
+ $cpuTime = $this->getTime( 'cpu' );
+ if ( $this->mCollateOnly ) {
+ $elapsedcpu = $cpuTime - $octime;
+ $elapsedreal = $realTime - $ortime;
+ $memchange = memory_get_usage() - $omem;
+ $this->updateEntry( $functionname, $elapsedcpu, $elapsedreal, $memchange );
+ } else {
+ $this->mStack[] = array_merge( $item,
+ array( $realTime, $cpuTime, memory_get_usage() ) );
}
- $bit[] = $time;
- $bit[] = $memory;
- $this->mStack[] = $bit;
- $this->updateTrxProfiling( $functionname, $time );
+ $this->updateTrxProfiling( $functionname, $realTime - $ortime );
}
}
}
}
+ /**
+ * Log the data to some store or even the page output
+ */
+ public function logData() {
+ /* Implement in subclasses */
+ }
+
/**
* Mark a DB as in a transaction with one or more writes pending
*
*
* @param $t Boolean
*/
- function setTemplated( $t ) {
+ public function setTemplated( $t ) {
$this->mTemplated = $t;
}
*/
public function getOutput() {
global $wgDebugFunctionEntry, $wgProfileCallTree;
- $wgDebugFunctionEntry = false;
+
+ $wgDebugFunctionEntry = false; // hack
if ( !count( $this->mStack ) && !count( $this->mCollated ) ) {
return "No profiling output\n";
* Returns a tree of function call instead of a list of functions
* @return string
*/
- function getCallTree() {
- return implode( '', array_map( array( &$this, 'getCallTreeLine' ), $this->remapCallTree( $this->mStack ) ) );
+ protected function getCallTree() {
+ return implode( '', array_map(
+ array( &$this, 'getCallTreeLine' ), $this->remapCallTree( $this->mStack )
+ ) );
}
/**
* @param array $stack profiling array
* @return array
*/
- function remapCallTree( $stack ) {
+ protected function remapCallTree( array $stack ) {
if ( count( $stack ) < 2 ) {
return $stack;
}
* Callback to get a formatted line for the call tree
* @return string
*/
- function getCallTreeLine( $entry ) {
- list( $fname, $level, $start, /* $x */, $end ) = $entry;
- $delta = $end - $start;
+ protected function getCallTreeLine( $entry ) {
+ 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 );
+ return sprintf( "%10s %s %s\n",
+ trim( sprintf( "%7.3f", $delta * 1000.0 ) ), $space, $fname );
}
/**
* - false (default): will fall back to default metric
* @return float|null
*/
- function getTime( $metric = false ) {
+ protected function getTime( $metric = false ) {
if ( $metric === false ) {
$metric = $this->mTimeMetric;
}
}
}
+ /**
+ * Populate mCollated
+ */
protected function collateData() {
if ( $this->mCollateDone ) {
return;
}
$this->mCollateDone = true;
+ $this->close(); // set "-total" entry
- $this->close();
+ if ( $this->mCollateOnly ) {
+ return; // already collated as methods exited
+ }
$this->mCollated = array();
- $this->mCalls = array();
- $this->mMemory = array();
# Estimate profiling overhead
$profileCount = count( $this->mStack );
# First, subtract the overhead!
$overheadTotal = $overheadMemory = $overheadInternal = array();
foreach ( $this->mStack as $entry ) {
+ // $entry is (name,pos,rtime0,cputime0,mem0,rtime1,cputime1,mem1)
$fname = $entry[0];
- $start = $entry[2];
- $end = $entry[4];
- $elapsed = $end - $start;
- $memory = $entry[5] - $entry[3];
+ $elapsed = $entry[5] - $entry[2];
+ $memchange = $entry[7] - $entry[4];
- if ( $fname == '-overhead-total' ) {
+ if ( $fname === '-overhead-total' ) {
$overheadTotal[] = $elapsed;
- $overheadMemory[] = $memory;
- } elseif ( $fname == '-overhead-internal' ) {
+ $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;
+ $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->mStack as $index => $entry ) {
+ // $entry is (name,pos,rtime0,cputime0,mem0,rtime1,cputime1,mem1)
$fname = $entry[0];
- $start = $entry[2];
- $end = $entry[4];
- $elapsed = $end - $start;
-
- $memory = $entry[5] - $entry[3];
+ $elapsedCpu = $entry[6] - $entry[3];
+ $elapsedReal = $entry[5] - $entry[2];
+ $memchange = $entry[7] - $entry[4];
$subcalls = $this->calltreeCount( $this->mStack, $index );
- if ( !preg_match( '/^-overhead/', $fname ) ) {
+ if ( substr( $fname, 0, 9 ) !== '-overhead' ) {
# Adjust for profiling overhead (except special values with elapsed=0
if ( $elapsed ) {
$elapsed -= $overheadInternal;
$elapsed -= ( $subcalls * $overheadTotal );
- $memory -= ( $subcalls * $overheadMemory );
+ $memchange -= ( $subcalls * $overheadMemory );
}
}
- if ( !array_key_exists( $fname, $this->mCollated ) ) {
- $this->mCollated[$fname] = 0;
- $this->mCalls[$fname] = 0;
- $this->mMemory[$fname] = 0;
- $this->mMin[$fname] = 1 << 24;
- $this->mMax[$fname] = 0;
- $this->mOverhead[$fname] = 0;
- $this->mPeriods[$fname] = array();
- }
-
- $this->mCollated[$fname] += $elapsed;
- $this->mCalls[$fname]++;
- $this->mMemory[$fname] += $memory;
- $this->mMin[$fname] = min( $this->mMin[$fname], $elapsed );
- $this->mMax[$fname] = max( $this->mMax[$fname], $elapsed );
- $this->mOverhead[$fname] += $subcalls;
- $this->mPeriods[$fname][] = compact( 'start', 'end', 'memory', 'subcalls' );
+ $period = array( 'start' => $entry[2], 'end' => $entry[5],
+ 'memory' => $memchange, 'subcalls' => $subcalls );
+ $this->updateEntry( $fname, $elapsedCpu, $elapsedReal, $memchange, $subcalls, $period );
}
- $this->mCalls['-overhead-total'] = $profileCount;
+ $this->mCollated['-overhead-total']['count'] = $profileCount;
arsort( $this->mCollated, SORT_NUMERIC );
}
*
* @return string
*/
- function getFunctionReport() {
+ protected function getFunctionReport() {
$this->collateData();
$width = 140;
$prof = "\nProfiling data\n";
$prof .= sprintf( $titleFormat, 'Name', 'Calls', 'Total', 'Each', '%', 'Mem' );
- $total = isset( $this->mCollated['-total'] ) ? $this->mCollated['-total'] : 0;
+ $total = isset( $this->mCollated['-total'] )
+ ? $this->mCollated['-total']['real']
+ : 0;
- foreach ( $this->mCollated as $fname => $elapsed ) {
- $calls = $this->mCalls[$fname];
- $percent = $total ? 100. * $elapsed / $total : 0;
- $memory = $this->mMemory[$fname];
+ foreach ( $this->mCollated as $fname => $data ) {
+ $calls = $data['count'];
+ $percent = $total ? 100 * $data['real'] / $total : 0;
+ $memory = $data['memory'];
$prof .= sprintf( $format,
substr( $fname, 0, $nameWidth ),
$calls,
- (float)( $elapsed * 1000 ),
- (float)( $elapsed * 1000 ) / $calls,
+ (float)( $data['real'] * 1000 ),
+ (float)( $data['real'] * 1000 ) / $calls,
$percent,
$memory,
- ( $this->mMin[$fname] * 1000.0 ),
- ( $this->mMax[$fname] * 1000.0 ),
- $this->mOverhead[$fname]
+ ( $data['min_real'] * 1000.0 ),
+ ( $data['max_real'] * 1000.0 ),
+ $data['overhead']
);
}
$prof .= "\nTotal: $total\n\n";
* @return array
*/
public function getRawData() {
+ // This method is called before shutdown in the footer method on Skins.
+ // If some outer methods have not yet called wfProfileOut(), work around
+ // that by clearing anything in the work stack to just the "-total" entry.
+ // Collate after doing this so the results do not include profile errors.
+ if ( count( $this->mWorkStack ) > 1 ) {
+ $oldWorkStack = $this->mWorkStack;
+ $this->mWorkStack = array( $this->mWorkStack[0] ); // just the "-total" one
+ } else {
+ $oldWorkStack = null;
+ }
$this->collateData();
+ // If this trick is used, then the old work stack is swapped back afterwards
+ // and mCollateDone is reset to false. This means that logData() will still
+ // make use of all the method data since the missing wfProfileOut() calls
+ // should be made by the time it is called.
+ if ( $oldWorkStack ) {
+ $this->mWorkStack = $oldWorkStack;
+ $this->mCollateDone = false;
+ }
+
+ $total = isset( $this->mCollated['-total'] )
+ ? $this->mCollated['-total']['real']
+ : 0;
$profile = array();
- $total = isset( $this->mCollated['-total'] ) ? $this->mCollated['-total'] : 0;
- foreach ( $this->mCollated as $fname => $elapsed ) {
+ foreach ( $this->mCollated as $fname => $data ) {
$periods = array();
- foreach ( $this->mPeriods[$fname] as $period ) {
+ foreach ( $data['periods'] as $period ) {
$period['start'] *= 1000;
$period['end'] *= 1000;
$periods[] = $period;
}
$profile[] = array(
'name' => $fname,
- 'calls' => $this->mCalls[$fname],
- 'elapsed' => $elapsed * 1000,
- 'percent' => $total ? 100. * $elapsed / $total : 0,
- 'memory' => $this->mMemory[$fname],
- 'min' => $this->mMin[$fname] * 1000,
- 'max' => $this->mMax[$fname] * 1000,
- 'overhead' => $this->mOverhead[$fname],
- 'periods' => $periods,
+ 'calls' => $data['count'],
+ 'elapsed' => $data['real'] * 1000,
+ 'percent' => $total ? 100 * $data['real'] / $total : 0,
+ 'memory' => $data['memory'],
+ 'min' => $data['min_real'] * 1000,
+ 'max' => $data['max_real'] * 1000,
+ 'overhead' => $data['overhead'],
+ 'periods' => $periods
);
}
* @param $stack Array:
* @param $start Integer:
* @return Integer
- * @private
*/
- function calltreeCount( $stack, $start ) {
+ protected function calltreeCount( $stack, $start ) {
$level = $stack[$start][1];
$count = 0;
for ( $i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i-- ) {
return $count;
}
- /**
- * Log the whole profiling data into the database.
- */
- public function logData() {
- global $wgProfilePerHost, $wgProfileToDatabase;
-
- # Do not log anything if database is readonly (bug 5375)
- if ( wfReadOnly() || !$wgProfileToDatabase ) {
- return;
- }
-
- $dbw = wfGetDB( DB_MASTER );
- if ( !is_object( $dbw ) ) {
- return;
- }
-
- if ( $wgProfilePerHost ) {
- $pfhost = wfHostname();
- } else {
- $pfhost = '';
- }
-
- try {
- $this->collateData();
-
- foreach ( $this->mCollated as $name => $elapsed ) {
- $eventCount = $this->mCalls[$name];
- $timeSum = (float)( $elapsed * 1000 );
- $memorySum = (float)$this->mMemory[$name];
- $name = substr( $name, 0, 255 );
-
- // Kludge
- $timeSum = $timeSum >= 0 ? $timeSum : 0;
- $memorySum = $memorySum >= 0 ? $memorySum : 0;
-
- $dbw->update( 'profiling',
- array(
- "pf_count=pf_count+{$eventCount}",
- "pf_time=pf_time+{$timeSum}",
- "pf_memory=pf_memory+{$memorySum}",
- ),
- array(
- 'pf_name' => $name,
- 'pf_server' => $pfhost,
- ),
- __METHOD__ );
-
- $rc = $dbw->affectedRows();
- if ( $rc == 0 ) {
- $dbw->insert( 'profiling', array( 'pf_name' => $name, 'pf_count' => $eventCount,
- 'pf_time' => $timeSum, 'pf_memory' => $memorySum, 'pf_server' => $pfhost ),
- __METHOD__, array( 'IGNORE' ) );
- }
- // When we upgrade to mysql 4.1, the insert+update
- // can be merged into just a insert with this construct added:
- // "ON DUPLICATE KEY UPDATE ".
- // "pf_count=pf_count + VALUES(pf_count), ".
- // "pf_time=pf_time + VALUES(pf_time)";
- }
- } catch ( DBError $e ) {}
- }
-
- /**
- * Get the function name of the current profiling section
- * @return
- */
- function getCurrentSection() {
- $elt = end( $this->mWorkStack );
- return $elt[0];
- }
-
/**
* Add an entry in the debug log file
*
* @param string $s to output
*/
- function debug( $s ) {
+ protected function debug( $s ) {
if ( function_exists( 'wfDebug' ) ) {
wfDebug( $s );
}
* @param string $group Group to send the message to
* @param string $s to output
*/
- function debugGroup( $group, $s ) {
+ protected function debugGroup( $group, $s ) {
if ( function_exists( 'wfDebugLog' ) ) {
wfDebugLog( $group, $s );
}