| 1 |
<?php |
| 2 |
|
| 3 |
namespace GeminiLabs\BlackBar; |
| 4 |
|
| 5 |
class Profiler |
| 6 |
{ |
| 7 |
/** |
| 8 |
* This is the time that WordPress takes to execute the profiler hook |
| 9 |
* @var int |
| 10 |
*/ |
| 11 |
protected $noise = 0; |
| 12 |
|
| 13 |
/** |
| 14 |
* @var int |
| 15 |
*/ |
| 16 |
protected $start = null; |
| 17 |
|
| 18 |
/** |
| 19 |
* @var int |
| 20 |
*/ |
| 21 |
protected $stop = null; |
| 22 |
|
| 23 |
/** |
| 24 |
* @var array |
| 25 |
*/ |
| 26 |
protected $timers = array(); |
| 27 |
|
| 28 |
/** |
| 29 |
* @return array |
| 30 |
*/ |
| 31 |
public function getMeasure() |
| 32 |
{ |
| 33 |
return $this->timers; |
| 34 |
} |
| 35 |
|
| 36 |
/** |
| 37 |
* @param array $timer |
| 38 |
* @return string |
| 39 |
*/ |
| 40 |
public function getMemoryString( $timer ) |
| 41 |
{ |
| 42 |
$timer = $this->normalize( $timer ); |
| 43 |
return sprintf( '%s kB', round( $timer['memory'] / 1000 )); |
| 44 |
} |
| 45 |
|
| 46 |
/** |
| 47 |
* @param array $timer |
| 48 |
* @return string |
| 49 |
*/ |
| 50 |
public function getNameString( $timer ) |
| 51 |
{ |
| 52 |
$timer = $this->normalize( $timer ); |
| 53 |
return $timer['name']; |
| 54 |
} |
| 55 |
|
| 56 |
/** |
| 57 |
* @param array $timer |
| 58 |
* @return string |
| 59 |
*/ |
| 60 |
public function getTimeString( $timer ) |
| 61 |
{ |
| 62 |
$timer = $this->normalize( $timer ); |
| 63 |
$index = array_search( $timer['name'], array_column( $this->timers, 'name' )); |
| 64 |
$start = $this->start + ( $index * $this->noise ); |
| 65 |
$time = number_format( round(( $timer['time'] - $start ) * 1000, 4 ), 4 ); |
| 66 |
return sprintf( '%s ms', $time ); |
| 67 |
} |
| 68 |
|
| 69 |
/** |
| 70 |
* @return int Microseconds |
| 71 |
*/ |
| 72 |
public function getTotalTime() |
| 73 |
{ |
| 74 |
$totalNoise = ( count( $this->timers ) - 1 ) * $this->noise; |
| 75 |
return $this->stop - $this->start - $totalNoise; |
| 76 |
} |
| 77 |
|
| 78 |
/** |
| 79 |
* @param string $name |
| 80 |
* @return void |
| 81 |
*/ |
| 82 |
public function trace( $name ) |
| 83 |
{ |
| 84 |
$microtime = microtime( true ); |
| 85 |
if( !$this->start ) { |
| 86 |
$this->start = $microtime; |
| 87 |
} |
| 88 |
if( $name === 'blackbar/profiler/noise' ) { |
| 89 |
$this->noise = $microtime - $this->start; |
| 90 |
return; |
| 91 |
} |
| 92 |
$this->timers[] = array( |
| 93 |
'memory' => memory_get_peak_usage(), |
| 94 |
'name' => $name, |
| 95 |
'time' => $microtime, |
| 96 |
); |
| 97 |
$this->stop = $microtime; |
| 98 |
} |
| 99 |
|
| 100 |
/** |
| 101 |
* @param array $timer |
| 102 |
* @return array |
| 103 |
*/ |
| 104 |
protected function normalize( $timer ) |
| 105 |
{ |
| 106 |
return wp_parse_args( (array)$timer, array( |
| 107 |
'memory' => 0, |
| 108 |
'name' => '', |
| 109 |
'time' => 0, |
| 110 |
)); |
| 111 |
} |
| 112 |
} |
| 113 |
|