3
declare(strict_types=1);
6
* This file is part of CodeIgniter 4 framework.
8
* (c) CodeIgniter Foundation <admin@codeigniter.com>
10
* For the full copyright and license information, please view
11
* the LICENSE file that was distributed with this source code.
14
namespace CodeIgniter\Debug;
21
* Provides a simple way to measure the amount of time
22
* that elapses between two points.
24
* @see \CodeIgniter\Debug\TimerTest
33
protected $timers = [];
36
* Starts a timer running.
38
* Multiple calls can be made to this method so that several
39
* execution points can be measured.
41
* @param string $name The name of this timer.
42
* @param float|null $time Allows user to provide time.
46
public function start(string $name, ?float $time = null)
48
$this->timers[strtolower($name)] = [
49
'start' => ! empty($time) ? $time : microtime(true),
57
* Stops a running timer.
59
* If the timer is not stopped before the timers() method is called,
60
* it will be automatically stopped at that point.
62
* @param string $name The name of this timer.
66
public function stop(string $name)
68
$name = strtolower($name);
70
if (empty($this->timers[$name])) {
71
throw new RuntimeException('Cannot stop timer: invalid name given.');
74
$this->timers[$name]['end'] = microtime(true);
80
* Returns the duration of a recorded timer.
82
* @param string $name The name of the timer.
83
* @param int $decimals Number of decimal places.
85
* @return float|null Returns null if timer does not exist by that name.
86
* Returns a float representing the number of
87
* seconds elapsed while that timer was running.
89
public function getElapsedTime(string $name, int $decimals = 4)
91
$name = strtolower($name);
93
if (empty($this->timers[$name])) {
97
$timer = $this->timers[$name];
99
if (empty($timer['end'])) {
100
$timer['end'] = microtime(true);
103
return (float) number_format($timer['end'] - $timer['start'], $decimals, '.', '');
107
* Returns the array of timers, with the duration pre-calculated for you.
109
* @param int $decimals Number of decimal places
111
public function getTimers(int $decimals = 4): array
113
$timers = $this->timers;
115
foreach ($timers as &$timer) {
116
if (empty($timer['end'])) {
117
$timer['end'] = microtime(true);
120
$timer['duration'] = (float) number_format($timer['end'] - $timer['start'], $decimals);
127
* Checks whether or not a timer with the specified name exists.
129
public function has(string $name): bool
131
return array_key_exists(strtolower($name), $this->timers);
135
* Executes callable and measures its time.
136
* Returns its return value if any.
138
* @param string $name The name of the timer
139
* @param callable(): mixed $callable callable to be executed
143
public function record(string $name, callable $callable)
146
$returnValue = $callable();