ci4

Форк
0
/
Timer.php 
151 строка · 3.7 Кб
1
<?php
2

3
declare(strict_types=1);
4

5
/**
6
 * This file is part of CodeIgniter 4 framework.
7
 *
8
 * (c) CodeIgniter Foundation <admin@codeigniter.com>
9
 *
10
 * For the full copyright and license information, please view
11
 * the LICENSE file that was distributed with this source code.
12
 */
13

14
namespace CodeIgniter\Debug;
15

16
use RuntimeException;
17

18
/**
19
 * Class Timer
20
 *
21
 * Provides a simple way to measure the amount of time
22
 * that elapses between two points.
23
 *
24
 * @see \CodeIgniter\Debug\TimerTest
25
 */
26
class Timer
27
{
28
    /**
29
     * List of all timers.
30
     *
31
     * @var array
32
     */
33
    protected $timers = [];
34

35
    /**
36
     * Starts a timer running.
37
     *
38
     * Multiple calls can be made to this method so that several
39
     * execution points can be measured.
40
     *
41
     * @param string     $name The name of this timer.
42
     * @param float|null $time Allows user to provide time.
43
     *
44
     * @return Timer
45
     */
46
    public function start(string $name, ?float $time = null)
47
    {
48
        $this->timers[strtolower($name)] = [
49
            'start' => ! empty($time) ? $time : microtime(true),
50
            'end'   => null,
51
        ];
52

53
        return $this;
54
    }
55

56
    /**
57
     * Stops a running timer.
58
     *
59
     * If the timer is not stopped before the timers() method is called,
60
     * it will be automatically stopped at that point.
61
     *
62
     * @param string $name The name of this timer.
63
     *
64
     * @return Timer
65
     */
66
    public function stop(string $name)
67
    {
68
        $name = strtolower($name);
69

70
        if (empty($this->timers[$name])) {
71
            throw new RuntimeException('Cannot stop timer: invalid name given.');
72
        }
73

74
        $this->timers[$name]['end'] = microtime(true);
75

76
        return $this;
77
    }
78

79
    /**
80
     * Returns the duration of a recorded timer.
81
     *
82
     * @param string $name     The name of the timer.
83
     * @param int    $decimals Number of decimal places.
84
     *
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.
88
     */
89
    public function getElapsedTime(string $name, int $decimals = 4)
90
    {
91
        $name = strtolower($name);
92

93
        if (empty($this->timers[$name])) {
94
            return null;
95
        }
96

97
        $timer = $this->timers[$name];
98

99
        if (empty($timer['end'])) {
100
            $timer['end'] = microtime(true);
101
        }
102

103
        return (float) number_format($timer['end'] - $timer['start'], $decimals, '.', '');
104
    }
105

106
    /**
107
     * Returns the array of timers, with the duration pre-calculated for you.
108
     *
109
     * @param int $decimals Number of decimal places
110
     */
111
    public function getTimers(int $decimals = 4): array
112
    {
113
        $timers = $this->timers;
114

115
        foreach ($timers as &$timer) {
116
            if (empty($timer['end'])) {
117
                $timer['end'] = microtime(true);
118
            }
119

120
            $timer['duration'] = (float) number_format($timer['end'] - $timer['start'], $decimals);
121
        }
122

123
        return $timers;
124
    }
125

126
    /**
127
     * Checks whether or not a timer with the specified name exists.
128
     */
129
    public function has(string $name): bool
130
    {
131
        return array_key_exists(strtolower($name), $this->timers);
132
    }
133

134
    /**
135
     * Executes callable and measures its time.
136
     * Returns its return value if any.
137
     *
138
     * @param string            $name     The name of the timer
139
     * @param callable(): mixed $callable callable to be executed
140
     *
141
     * @return mixed
142
     */
143
    public function record(string $name, callable $callable)
144
    {
145
        $this->start($name);
146
        $returnValue = $callable();
147
        $this->stop($name);
148

149
        return $returnValue;
150
    }
151
}
152

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.