Time::HiRes#

📦 std

High-resolution timers and sleeps: microsecond gettimeofday, sub-second sleep, alarm, and POSIX clocks.

Where the built-in time, sleep and alarm work in whole seconds, these take and return fractional ones. Use clock_gettime with CLOCK_MONOTONIC to measure an elapsed interval: it cannot jump backwards the way wall-clock time can.

This is Time::HiRes 1.978; Time/HiRes.pm is upstream’s. Nothing is exported by default; use Time::HiRes qw(time sleep alarm) replaces the built-ins in the importing package.

Synopsis#

use Time::HiRes qw(time sleep gettimeofday tv_interval clock_gettime CLOCK_MONOTONIC);

my $t0 = time;                          # e.g. 1700000000.123456
sleep 0.25;                             # a quarter of a second
printf "%.2f\n", time - $t0;            # about 0.25

my @start = gettimeofday;               # (seconds, microseconds)
my $elapsed = tv_interval(\@start);     # seconds since then, as a float

my $m0 = clock_gettime(CLOCK_MONOTONIC);    # for intervals: never jumps back
my $dt = clock_gettime(CLOCK_MONOTONIC) - $m0;

tv_interval($start, $end) (written in Perl) is the time between two gettimeofday pairs, $end defaulting to now. The clock constants (CLOCK_REALTIME, CLOCK_MONOTONIC, CLOCK_PROCESS_CPUTIME_ID, …) and ITIMER_REAL/ITIMER_VIRTUAL/ITIMER_PROF for setitimer are exported on request.

Differences from upstream#

None: upstream’s tests pass unchanged (t/81-xs-native/Time-HiRes, the upstream files), and the rest there checks against perl 5.44.

Functions#

Other Functions#

time#

Return the current epoch time as a float, with sub-second precision.

gettimeofday#

Return the current time as ($seconds, $microseconds).

usleep#

Sleep for the given number of MICROseconds.

nanosleep#

Sleep for the given number of NANOseconds.

sleep#

Sleep for a possibly fractional number of seconds.

alarm#

Schedule a SIGALRM after a possibly fractional delay.

ualarm#

Schedule a SIGALRM after a delay given in MICROseconds.

setitimer#

Arm one of the interval timers (ITIMER_REAL and friends).

getitimer#

Return an interval timer’s current ($value, $interval) without changing it.

clock_gettime#

Read the named POSIX clock, returning the time as a float.

clock_getres#

Return the resolution of the named POSIX clock, in seconds.

clock#

Return processor time consumed by this process, in seconds.

clock_nanosleep#

Sleep against a named POSIX clock, in nanoseconds.

utime#

Set access and modification times on files, with sub-second precision.

stat#

The built-in stat, with the access, modification and change times (elements 8, 9 and 10) in fractional seconds, as precise as the file system keeps them. Takes a file name or a filehandle, $_ when omitted; returns the empty list for a file that cannot be stat’ed, with $! set.

lstat#

stat for a symbolic link itself rather than what it points to, as the built-in lstat, with fractional times.

tv_interval#

tv_interval(\@t0, \@t1?) - pure Perl in HiRes.pm