Chris@0
|
1 <?php
|
Chris@0
|
2
|
Chris@0
|
3 namespace Drupal\Component\Utility;
|
Chris@0
|
4
|
Chris@0
|
5 /**
|
Chris@0
|
6 * Provides helpers to use timers throughout a request.
|
Chris@0
|
7 *
|
Chris@0
|
8 * @ingroup utility
|
Chris@0
|
9 */
|
Chris@0
|
10 class Timer {
|
Chris@0
|
11
|
Chris@18
|
12 protected static $timers = [];
|
Chris@0
|
13
|
Chris@0
|
14 /**
|
Chris@0
|
15 * Starts the timer with the specified name.
|
Chris@0
|
16 *
|
Chris@0
|
17 * If you start and stop the same timer multiple times, the measured intervals
|
Chris@0
|
18 * will be accumulated.
|
Chris@0
|
19 *
|
Chris@0
|
20 * @param $name
|
Chris@0
|
21 * The name of the timer.
|
Chris@0
|
22 */
|
Chris@0
|
23 public static function start($name) {
|
Chris@0
|
24 static::$timers[$name]['start'] = microtime(TRUE);
|
Chris@0
|
25 static::$timers[$name]['count'] = isset(static::$timers[$name]['count']) ? ++static::$timers[$name]['count'] : 1;
|
Chris@0
|
26 }
|
Chris@0
|
27
|
Chris@0
|
28 /**
|
Chris@0
|
29 * Reads the current timer value without stopping the timer.
|
Chris@0
|
30 *
|
Chris@0
|
31 * @param string $name
|
Chris@0
|
32 * The name of the timer.
|
Chris@0
|
33 *
|
Chris@0
|
34 * @return int
|
Chris@0
|
35 * The current timer value in ms.
|
Chris@0
|
36 */
|
Chris@0
|
37 public static function read($name) {
|
Chris@0
|
38 if (isset(static::$timers[$name]['start'])) {
|
Chris@0
|
39 $stop = microtime(TRUE);
|
Chris@0
|
40 $diff = round(($stop - static::$timers[$name]['start']) * 1000, 2);
|
Chris@0
|
41
|
Chris@0
|
42 if (isset(static::$timers[$name]['time'])) {
|
Chris@0
|
43 $diff += static::$timers[$name]['time'];
|
Chris@0
|
44 }
|
Chris@0
|
45 return $diff;
|
Chris@0
|
46 }
|
Chris@0
|
47 return static::$timers[$name]['time'];
|
Chris@0
|
48 }
|
Chris@0
|
49
|
Chris@0
|
50 /**
|
Chris@0
|
51 * Stops the timer with the specified name.
|
Chris@0
|
52 *
|
Chris@0
|
53 * @param string $name
|
Chris@0
|
54 * The name of the timer.
|
Chris@0
|
55 *
|
Chris@0
|
56 * @return array
|
Chris@0
|
57 * A timer array. The array contains the number of times the timer has been
|
Chris@0
|
58 * started and stopped (count) and the accumulated timer value in ms (time).
|
Chris@0
|
59 */
|
Chris@0
|
60 public static function stop($name) {
|
Chris@0
|
61 if (isset(static::$timers[$name]['start'])) {
|
Chris@0
|
62 $stop = microtime(TRUE);
|
Chris@0
|
63 $diff = round(($stop - static::$timers[$name]['start']) * 1000, 2);
|
Chris@0
|
64 if (isset(static::$timers[$name]['time'])) {
|
Chris@0
|
65 static::$timers[$name]['time'] += $diff;
|
Chris@0
|
66 }
|
Chris@0
|
67 else {
|
Chris@0
|
68 static::$timers[$name]['time'] = $diff;
|
Chris@0
|
69 }
|
Chris@0
|
70 unset(static::$timers[$name]['start']);
|
Chris@0
|
71 }
|
Chris@0
|
72
|
Chris@0
|
73 return static::$timers[$name];
|
Chris@0
|
74 }
|
Chris@0
|
75
|
Chris@0
|
76 }
|