3 namespace Drupal\Component\Utility;
6 * Provides helpers to use timers throughout a request.
12 static protected $timers = [];
15 * Starts the timer with the specified name.
17 * If you start and stop the same timer multiple times, the measured intervals
18 * will be accumulated.
21 * The name of the timer.
23 static public function start($name) {
24 static::$timers[$name]['start'] = microtime(TRUE);
25 static::$timers[$name]['count'] = isset(static::$timers[$name]['count']) ? ++static::$timers[$name]['count'] : 1;
29 * Reads the current timer value without stopping the timer.
32 * The name of the timer.
35 * The current timer value in ms.
37 static public function read($name) {
38 if (isset(static::$timers[$name]['start'])) {
39 $stop = microtime(TRUE);
40 $diff = round(($stop - static::$timers[$name]['start']) * 1000, 2);
42 if (isset(static::$timers[$name]['time'])) {
43 $diff += static::$timers[$name]['time'];
47 return static::$timers[$name]['time'];
51 * Stops the timer with the specified name.
54 * The name of the timer.
57 * A timer array. The array contains the number of times the timer has been
58 * started and stopped (count) and the accumulated timer value in ms (time).
60 static public function stop($name) {
61 if (isset(static::$timers[$name]['start'])) {
62 $stop = microtime(TRUE);
63 $diff = round(($stop - static::$timers[$name]['start']) * 1000, 2);
64 if (isset(static::$timers[$name]['time'])) {
65 static::$timers[$name]['time'] += $diff;
68 static::$timers[$name]['time'] = $diff;
70 unset(static::$timers[$name]['start']);
73 return static::$timers[$name];