Clock.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace Tools\Utility;
  3. class Clock {
  4. /**
  5. * @var float
  6. */
  7. protected static $_counterStartTime = 0.0;
  8. /**
  9. * Returns microtime as float value
  10. * (to be subtracted right away)
  11. *
  12. * @param int $precision
  13. *
  14. * @return float
  15. */
  16. public static function microtime(int $precision = 8): float {
  17. return round(microtime(true), $precision);
  18. }
  19. /**
  20. * @return void
  21. */
  22. public static function startClock(): void {
  23. static::$_counterStartTime = static::microtime();
  24. }
  25. /**
  26. * @param int $precision
  27. * @param bool $restartClock
  28. * @return float
  29. */
  30. public static function returnElapsedTime($precision = 8, $restartClock = false): float {
  31. $startTime = static::$_counterStartTime;
  32. if ($restartClock) {
  33. static::startClock();
  34. }
  35. return static::calcElapsedTime($startTime, static::microtime(), $precision);
  36. }
  37. /**
  38. * Returns microtime as float value
  39. * (to be subtracted right away)
  40. *
  41. * @param float $start
  42. * @param float $end
  43. * @param int $precision
  44. * @return float
  45. */
  46. public static function calcElapsedTime($start, $end, $precision = 8) {
  47. $elapsed = $end - $start;
  48. return round($elapsed, $precision);
  49. }
  50. }