Timer.php 1.9 KB

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