Last active
August 17, 2026 10:40
-
-
Save ArrayIterator/4d1c54d3b7e8e78cb217c3c76f74973b to your computer and use it in GitHub Desktop.
PHP Better Precise Time Unit than microtime()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| declare(strict_types=1); | |
| use function hrtime; | |
| use function intdiv; | |
| use function microtime; | |
| /** | |
| * Time helper class to get the current time in milliseconds, microseconds, and nanoseconds | |
| * Use boot time to get the time since the application booted and more precise time than microtime | |
| */ | |
| final class Time | |
| { | |
| /** | |
| * @var int $bootTimeNano The boot time in nanoseconds | |
| */ | |
| private static int $bootTimeNano; | |
| /** | |
| * Get the boot time in nanoseconds | |
| * | |
| * @return int | |
| */ | |
| public static function boot(): int | |
| { | |
| return self::$bootTimeNano ??= (int)(microtime(true) * 1_000_000_000) - hrtime(true); | |
| } | |
| /** | |
| * Get the current second time | |
| * | |
| * @return int | |
| */ | |
| public static function second() : int | |
| { | |
| return intdiv(self::nano(), 1_000_000_000); | |
| } | |
| /** | |
| * Get the current millisecond time | |
| * | |
| * @return int | |
| */ | |
| public static function milli() : int | |
| { | |
| return intdiv(self::nano(), 1_000_000); | |
| } | |
| /** | |
| * Get the current micro time | |
| * | |
| * @return int | |
| */ | |
| public static function micro() : int | |
| { | |
| return intdiv(self::nano(), 1_000); | |
| } | |
| /** | |
| * Get the current nano time | |
| * | |
| * @return int | |
| */ | |
| public static function nano() : int | |
| { | |
| return self::boot() + hrtime(true); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment