Timer.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php declare(strict_types=1);
  2. /*
  3. * This file is part of phpunit/php-timer.
  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. namespace SebastianBergmann\Timer;
  11. final class Timer
  12. {
  13. /**
  14. * @var int[]
  15. */
  16. private static $sizes = [
  17. 'GB' => 1073741824,
  18. 'MB' => 1048576,
  19. 'KB' => 1024,
  20. ];
  21. /**
  22. * @var int[]
  23. */
  24. private static $times = [
  25. 'hour' => 3600000,
  26. 'minute' => 60000,
  27. 'second' => 1000,
  28. ];
  29. /**
  30. * @var float[]
  31. */
  32. private static $startTimes = [];
  33. public static function start(): void
  34. {
  35. self::$startTimes[] = \microtime(true);
  36. }
  37. public static function stop(): float
  38. {
  39. return \microtime(true) - \array_pop(self::$startTimes);
  40. }
  41. public static function bytesToString(float $bytes): string
  42. {
  43. foreach (self::$sizes as $unit => $value) {
  44. if ($bytes >= $value) {
  45. return \sprintf('%.2f %s', $bytes >= 1024 ? $bytes / $value : $bytes, $unit);
  46. }
  47. }
  48. return $bytes . ' byte' . ((int) $bytes !== 1 ? 's' : '');
  49. }
  50. public static function secondsToTimeString(float $time): string
  51. {
  52. $ms = \round($time * 1000);
  53. foreach (self::$times as $unit => $value) {
  54. if ($ms >= $value) {
  55. $time = \floor($ms / $value * 100.0) / 100.0;
  56. return $time . ' ' . ($time == 1 ? $unit : $unit . 's');
  57. }
  58. }
  59. return $ms . ' ms';
  60. }
  61. /**
  62. * @throws RuntimeException
  63. */
  64. public static function timeSinceStartOfRequest(): string
  65. {
  66. if (isset($_SERVER['REQUEST_TIME_FLOAT'])) {
  67. $startOfRequest = $_SERVER['REQUEST_TIME_FLOAT'];
  68. } elseif (isset($_SERVER['REQUEST_TIME'])) {
  69. $startOfRequest = $_SERVER['REQUEST_TIME'];
  70. } else {
  71. throw new RuntimeException('Cannot determine time at which the request started');
  72. }
  73. return self::secondsToTimeString(\microtime(true) - $startOfRequest);
  74. }
  75. /**
  76. * @throws RuntimeException
  77. */
  78. public static function resourceUsage(): string
  79. {
  80. return \sprintf(
  81. 'Time: %s, Memory: %s',
  82. self::timeSinceStartOfRequest(),
  83. self::bytesToString(\memory_get_peak_usage(true))
  84. );
  85. }
  86. }