StopwatchPeriod.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  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 Symfony\Component\Stopwatch;
  11. /**
  12. * Represents an Period for an Event.
  13. *
  14. * @author Fabien Potencier <fabien@symfony.com>
  15. */
  16. class StopwatchPeriod
  17. {
  18. private $start;
  19. private $end;
  20. private $memory;
  21. /**
  22. * @param int|float $start The relative time of the start of the period (in milliseconds)
  23. * @param int|float $end The relative time of the end of the period (in milliseconds)
  24. * @param bool $morePrecision If true, time is stored as float to keep the original microsecond precision
  25. */
  26. public function __construct($start, $end, bool $morePrecision = false)
  27. {
  28. $this->start = $morePrecision ? (float) $start : (int) $start;
  29. $this->end = $morePrecision ? (float) $end : (int) $end;
  30. $this->memory = memory_get_usage(true);
  31. }
  32. /**
  33. * Gets the relative time of the start of the period.
  34. *
  35. * @return int|float The time (in milliseconds)
  36. */
  37. public function getStartTime()
  38. {
  39. return $this->start;
  40. }
  41. /**
  42. * Gets the relative time of the end of the period.
  43. *
  44. * @return int|float The time (in milliseconds)
  45. */
  46. public function getEndTime()
  47. {
  48. return $this->end;
  49. }
  50. /**
  51. * Gets the time spent in this period.
  52. *
  53. * @return int|float The period duration (in milliseconds)
  54. */
  55. public function getDuration()
  56. {
  57. return $this->end - $this->start;
  58. }
  59. /**
  60. * Gets the memory usage.
  61. *
  62. * @return int The memory usage (in bytes)
  63. */
  64. public function getMemory()
  65. {
  66. return $this->memory;
  67. }
  68. public function __toString(): string
  69. {
  70. return sprintf('%.2F MiB - %d ms', $this->getMemory() / 1024 / 1024, $this->getDuration());
  71. }
  72. }