| 1 |
<?php |
| 2 |
|
| 3 |
namespace GeminiLabs\BlackBar\Modules; |
| 4 |
|
| 5 |
class Profiler extends Module |
| 6 |
{ |
| 7 |
/** |
| 8 |
* @var int |
| 9 |
*/ |
| 10 |
protected $memory_start = 0; |
| 11 |
/** |
| 12 |
* @var int |
| 13 |
*/ |
| 14 |
protected $memory_stop = 0; |
| 15 |
/** |
| 16 |
* The profiler noise to remove from the timer (in nanoseconds). |
| 17 |
* @var int |
| 18 |
*/ |
| 19 |
protected $noise = 0; |
| 20 |
/** |
| 21 |
* The hrtime the profiler started measuring (in nanoseconds). |
| 22 |
* @var int |
| 23 |
*/ |
| 24 |
protected $start = 0; |
| 25 |
/** |
| 26 |
* The hrtime the profiler stopped measuring (in nanoseconds). |
| 27 |
* @var int |
| 28 |
*/ |
| 29 |
protected $stop = 0; |
| 30 |
/** |
| 31 |
* @var array |
| 32 |
*/ |
| 33 |
protected $timer = []; |
| 34 |
|
| 35 |
public function entries(): array |
| 36 |
{ |
| 37 |
$entries = []; |
| 38 |
foreach ($this->entries as $entry) { |
| 39 |
$entry['time'] = $this->formatTime($entry['time']); |
| 40 |
$entries[] = $entry; |
| 41 |
} |
| 42 |
return $entries; |
| 43 |
} |
| 44 |
|
| 45 |
public function icon(): string |
| 46 |
{ |
| 47 |
return 'dashicons-performance'; |
| 48 |
} |
| 49 |
|
| 50 |
public function isVisible(): bool |
| 51 |
{ |
| 52 |
return $this->hasEntries(); |
| 53 |
} |
| 54 |
|
| 55 |
public function label(): string |
| 56 |
{ |
| 57 |
return __('Profiler', 'blackbar'); |
| 58 |
} |
| 59 |
|
| 60 |
public function set(string $property): void |
| 61 |
{ |
| 62 |
if ('noise' === $property) { |
| 63 |
$this->noise = (int) hrtime(true) - $this->start; |
| 64 |
} elseif ('start' === $property) { |
| 65 |
$this->start = (int) hrtime(true); |
| 66 |
$this->memory_start = memory_get_peak_usage(); |
| 67 |
} elseif ('stop' === $property) { |
| 68 |
$this->stop = (int) hrtime(true); |
| 69 |
$this->memory_stop = memory_get_peak_usage(); |
| 70 |
} |
| 71 |
} |
| 72 |
|
| 73 |
public function start(string $name): void |
| 74 |
{ |
| 75 |
$this->timer = [ |
| 76 |
'memory' => memory_get_peak_usage(), |
| 77 |
'name' => $name, |
| 78 |
'start' => (int) hrtime(true), |
| 79 |
'stop' => 0, |
| 80 |
'time' => 0, |
| 81 |
]; |
| 82 |
} |
| 83 |
|
| 84 |
public function stop(): void |
| 85 |
{ |
| 86 |
if (!empty($this->timer)) { |
| 87 |
$nanoseconds = (int) hrtime(true); |
| 88 |
$this->timer['memory'] = max(0, memory_get_peak_usage() - $this->timer['memory']); |
| 89 |
$this->timer['stop'] = $nanoseconds; |
| 90 |
$this->timer['time'] = max(0, $nanoseconds - $this->timer['start'] - $this->noise); |
| 91 |
$this->entries[] = $this->timer; |
| 92 |
$this->timer = []; // reset timer |
| 93 |
} |
| 94 |
} |
| 95 |
} |
| 96 |
|