ResourceUsageFormatter.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. use function is_float;
  12. use function memory_get_peak_usage;
  13. use function microtime;
  14. use function sprintf;
  15. final class ResourceUsageFormatter
  16. {
  17. /**
  18. * @psalm-var array<string,int>
  19. */
  20. private const SIZES = [
  21. 'GB' => 1073741824,
  22. 'MB' => 1048576,
  23. 'KB' => 1024,
  24. ];
  25. public function resourceUsage(Duration $duration): string
  26. {
  27. return sprintf(
  28. 'Time: %s, Memory: %s',
  29. $duration->asString(),
  30. $this->bytesToString(memory_get_peak_usage(true))
  31. );
  32. }
  33. /**
  34. * @throws TimeSinceStartOfRequestNotAvailableException
  35. */
  36. public function resourceUsageSinceStartOfRequest(): string
  37. {
  38. if (!isset($_SERVER['REQUEST_TIME_FLOAT'])) {
  39. throw new TimeSinceStartOfRequestNotAvailableException(
  40. 'Cannot determine time at which the request started because $_SERVER[\'REQUEST_TIME_FLOAT\'] is not available'
  41. );
  42. }
  43. if (!is_float($_SERVER['REQUEST_TIME_FLOAT'])) {
  44. throw new TimeSinceStartOfRequestNotAvailableException(
  45. 'Cannot determine time at which the request started because $_SERVER[\'REQUEST_TIME_FLOAT\'] is not of type float'
  46. );
  47. }
  48. return $this->resourceUsage(
  49. Duration::fromMicroseconds(
  50. (1000000 * (microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']))
  51. )
  52. );
  53. }
  54. private function bytesToString(int $bytes): string
  55. {
  56. foreach (self::SIZES as $unit => $value) {
  57. if ($bytes >= $value) {
  58. return sprintf('%.2f %s', $bytes >= 1024 ? $bytes / $value : $bytes, $unit);
  59. }
  60. }
  61. // @codeCoverageIgnoreStart
  62. return $bytes . ' byte' . ($bytes !== 1 ? 's' : '');
  63. // @codeCoverageIgnoreEnd
  64. }
  65. }