1 | <?php |
||
2 | /** |
||
3 | * Created by Gorlum 05.08.2018 8:05 |
||
4 | */ |
||
5 | |||
6 | class Timer { |
||
7 | /** |
||
8 | * @var array[] $times [ |
||
9 | * 'time' => (float)microtime(true), |
||
10 | * 'location' => (string)filename&line, |
||
11 | * 'message' => (string)attachedMessage |
||
12 | * ] |
||
13 | */ |
||
14 | private static $times = []; |
||
15 | |||
16 | public static function init() { |
||
17 | if (empty(static::$times)) { |
||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
18 | static::$times[] = ['time' => microtime(true)]; |
||
19 | } |
||
20 | } |
||
21 | |||
22 | /** |
||
23 | * @param string $message Message to attach to timestamp |
||
24 | */ |
||
25 | public static function mark($message = '') { |
||
26 | static::init(); |
||
27 | |||
28 | foreach (debug_backtrace() as $trace) { |
||
29 | if (empty($trace['class']) || $trace['class'] != static::class) { |
||
30 | break; |
||
31 | } |
||
32 | |||
33 | $realCall = $trace; |
||
34 | } |
||
35 | |||
36 | static::$times[] = [ |
||
0 ignored issues
–
show
|
|||
37 | 'time' => microtime(true), |
||
38 | 'location' => $realCall['file'] . '@' . $realCall['line'], |
||
0 ignored issues
–
show
Comprehensibility
Best Practice
introduced
by
|
|||
39 | 'message' => $message, |
||
40 | ]; |
||
41 | } |
||
42 | |||
43 | |||
44 | /** |
||
45 | * @param string $message |
||
46 | * |
||
47 | * @param bool $fromStart |
||
48 | * |
||
49 | * @return string |
||
50 | */ |
||
51 | public static function elapsed($message = '', $fromStart = false) { |
||
52 | $prevTime = $fromStart ? static::first()['time'] : static::last()['time']; |
||
53 | |||
54 | static::mark($message); |
||
55 | |||
56 | empty($prevTime) ? $prevTime = static::first()['time'] : false; |
||
57 | |||
58 | return number_format(static::last()['time'] - $prevTime, 6) . 's'; |
||
59 | } |
||
60 | |||
61 | public static function msg($message, $fromStart = false) { |
||
62 | |||
63 | $message . |
||
64 | ($fromStart ? ' FROM START ' : ' in ') . |
||
65 | static::elapsed($message, $fromStart) . |
||
66 | ' ---- ' . static::last()['location'] . |
||
67 | "\n<br />"; |
||
68 | } |
||
69 | |||
70 | /** |
||
71 | * @return mixed |
||
72 | */ |
||
73 | public static function last() { |
||
74 | return end(static::$times); |
||
0 ignored issues
–
show
|
|||
75 | } |
||
76 | |||
77 | /** |
||
78 | * @return mixed |
||
79 | */ |
||
80 | public static function first() { |
||
81 | return reset(static::$times); |
||
0 ignored issues
–
show
|
|||
82 | } |
||
83 | |||
84 | public static function getLog() { |
||
85 | return static::$times; |
||
0 ignored issues
–
show
|
|||
86 | } |
||
87 | |||
88 | } |
||
89 |