Timer.php 930 B

12345678910111213141516171819202122232425262728293031323334353637383940
  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 array_pop;
  12. use function hrtime;
  13. final class Timer
  14. {
  15. /**
  16. * @psalm-var list<float>
  17. */
  18. private array $startTimes = [];
  19. public function start(): void
  20. {
  21. $this->startTimes[] = (float) hrtime(true);
  22. }
  23. /**
  24. * @throws NoActiveTimerException
  25. */
  26. public function stop(): Duration
  27. {
  28. if (empty($this->startTimes)) {
  29. throw new NoActiveTimerException(
  30. 'Timer::start() has to be called before Timer::stop()'
  31. );
  32. }
  33. return Duration::fromNanoseconds((float) hrtime(true) - array_pop($this->startTimes));
  34. }
  35. }