summaryrefslogtreecommitdiff
path: root/vendor/open-telemetry/sdk/Common/Time/SystemClock.php
blob: f57e984900d81353d64849b7853494c20f0c2035 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php

declare(strict_types=1);

namespace OpenTelemetry\SDK\Common\Time;

use function hrtime;
use function microtime;

final class SystemClock implements ClockInterface
{
    private static int $referenceTime = 0;

    public function __construct()
    {
        self::init();
    }

    public static function create(): self
    {
        return new self();
    }

    /** @inheritDoc */
    public function now(): int
    {
        return self::$referenceTime + hrtime(true);
    }

    private static function init(): void
    {
        if (self::$referenceTime > 0) {
            return;
        }

        self::$referenceTime = self::calculateReferenceTime(
            microtime(true),
            hrtime(true)
        );
    }

    /**
     * Calculates the reference time which is later used to calculate the current wall clock time in nanoseconds by adding the current uptime.
     */
    private static function calculateReferenceTime(float $wallClockMicroTime, int $upTime): int
    {
        return ((int) ($wallClockMicroTime * ClockInterface::NANOS_PER_SECOND)) - $upTime;
    }
}