|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Symfony package. |
| 5 | + * |
| 6 | + * (c) Fabien Potencier <fabien@symfony.com> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +namespace Symfony\Component\Clock; |
| 13 | + |
D306
| 14 | +/** |
| 15 | + * A monotonic clock suitable for performance profiling. |
| 16 | + * |
| 17 | + * @author Nicolas Grekas <p@tchwork.com> |
| 18 | + */ |
| 19 | +final class MonotonicClock implements ClockInterface |
| 20 | +{ |
| 21 | + private int $sOffset; |
| 22 | + private int $usOffset; |
| 23 | + private \DateTimeZone $timezone; |
| 24 | + |
| 25 | + public function __construct(\DateTimeZone|string $timezone = null) |
| 26 | + { |
| 27 | + if (false === $offset = hrtime()) { |
| 28 | + throw new \RuntimeException('hrtime() returned false: the runtime environment does not provide access to a monotonic timer.'); |
| 29 | + } |
| 30 | + |
| 31 | + $time = gettimeofday(); |
| 32 | + $this->sOffset = $time['sec'] - $offset[0]; |
| 33 | + $this->usOffset = $time['usec'] - (int) ($offset[1] / 1000); |
| 34 | + |
| 35 | + if (\is_string($timezone ??= date_default_timezone_get())) { |
| 36 | + $this->timezone = new \DateTimeZone($timezone); |
| 37 | + } else { |
| 38 | + $this->timezone = $timezone; |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + public function now(): \DateTimeImmutable |
| 43 | + { |
| 44 | + [$s, $us] = hrtime(); |
| 45 | + |
| 46 | + if (1000000 <= $us = (int) ($us / 1000) + $this->usOffset) { |
| 47 | + ++$s; |
| 48 | + $us -= 1000000; |
| 49 | + } elseif (0 > $us) { |
| 50 | + --$s; |
| 51 | + $us += 1000000; |
| 52 | + } |
| 53 | + |
| 54 | + if (6 !== \strlen($now = (string) $us)) { |
| 55 | + $now = str_pad($now, 6, '0', \STR_PAD_LEFT); |
| 56 | + } |
| 57 | + |
| 58 | + $now = '@'.($s + $this->sOffset).'.'.$now; |
| 59 | + |
| 60 | + return (new \DateTimeImmutable($now, $this->timezone))->setTimezone($this->timezone); |
| 61 | + } |
| 62 | + |
| 63 | + public function sleep(float|int $seconds): void |
| 64 | + { |
| 65 | + if (0 < $s = (int) $seconds) { |
| 66 | + sleep($s); |
| 67 | + } |
| 68 | + |
| 69 | + if (0 < $us = $seconds - $s) { |
| 70 | + usleep($us * 1E6); |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + public function withTimeZone(\DateTimeZone|string $timezone): static |
| 75 | + { |
| 76 | + $clone = clone $this; |
| 77 | + $clone->timezone = \is_string($timezone) ? new \DateTimeZone($timezone) : $timezone; |
| 78 | + |
| 79 | + return $clone; |
| 80 | + } |
| 81 | +} |
0 commit comments