Timer.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. /*
  3. * This file is part of the PHP_Timer package.
  4. *
  5. * (c) Sebastian Bergmann <sebastian@phpunit.de>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. /**
  11. * Utility class for timing.
  12. */
  13. class PHP_Timer
  14. {
  15. /**
  16. * @var array
  17. */
  18. private static $times = array(
  19. 'hour' => 3600000,
  20. 'minute' => 60000,
  21. 'second' => 1000
  22. );
  23. /**
  24. * @var array
  25. */
  26. private static $startTimes = array();
  27. /**
  28. * @var float
  29. */
  30. public static $requestTime;
  31. /**
  32. * Starts the timer.
  33. */
  34. public static function start()
  35. {
  36. array_push(self::$startTimes, microtime(true));
  37. }
  38. /**
  39. * Stops the timer and returns the elapsed time.
  40. *
  41. * @return float
  42. */
  43. public static function stop()
  44. {
  45. return microtime(true) - array_pop(self::$startTimes);
  46. }
  47. /**
  48. * Formats the elapsed time as a string.
  49. *
  50. * @param float $time
  51. * @return string
  52. */
  53. public static function secondsToTimeString($time)
  54. {
  55. $ms = round($time * 1000);
  56. foreach (self::$times as $unit => $value) {
  57. if ($ms >= $value) {
  58. $time = floor($ms / $value * 100.0) / 100.0;
  59. return $time . ' ' . ($time == 1 ? $unit : $unit . 's');
  60. }
  61. }
  62. return $ms . ' ms';
  63. }
  64. /**
  65. * Formats the elapsed time since the start of the request as a string.
  66. *
  67. * @return string
  68. */
  69. public static function timeSinceStartOfRequest()
  70. {
  71. return self::secondsToTimeString(microtime(true) - self::$requestTime);
  72. }
  73. /**
  74. * Returns the resources (time, memory) of the request as a string.
  75. *
  76. * @return string
  77. */
  78. public static function resourceUsage()
  79. {
  80. return sprintf(
  81. 'Time: %s, Memory: %4.2fMB',
  82. self::timeSinceStartOfRequest(),
  83. memory_get_peak_usage(true) / 1048576
  84. );
  85. }
  86. }
  87. if (isset($_SERVER['REQUEST_TIME_FLOAT'])) {
  88. PHP_Timer::$requestTime = $_SERVER['REQUEST_TIME_FLOAT'];
  89. } elseif (isset($_SERVER['REQUEST_TIME'])) {
  90. PHP_Timer::$requestTime = $_SERVER['REQUEST_TIME'];
  91. } else {
  92. PHP_Timer::$requestTime = microtime(true);
  93. }