1HiRes(3)              User Contributed Perl Documentation             HiRes(3)
2
3
4

NAME

6       Time::HiRes - High resolution alarm, sleep, gettimeofday, interval
7       timers
8

SYNOPSIS

10         use Time::HiRes qw( usleep ualarm gettimeofday tv_interval nanosleep
11                             clock_gettime clock_getres clock_nanosleep clock
12                             stat lstat utime);
13
14         usleep ($microseconds);
15         nanosleep ($nanoseconds);
16
17         ualarm ($microseconds);
18         ualarm ($microseconds, $interval_microseconds);
19
20         $t0 = [gettimeofday];
21         ($seconds, $microseconds) = gettimeofday;
22
23         $elapsed = tv_interval ( $t0, [$seconds, $microseconds]);
24         $elapsed = tv_interval ( $t0, [gettimeofday]);
25         $elapsed = tv_interval ( $t0 );
26
27         use Time::HiRes qw ( time alarm sleep );
28
29         $now_fractions = time;
30         sleep ($floating_seconds);
31         alarm ($floating_seconds);
32         alarm ($floating_seconds, $floating_interval);
33
34         use Time::HiRes qw( setitimer getitimer );
35
36         setitimer ($which, $floating_seconds, $floating_interval );
37         getitimer ($which);
38
39         use Time::HiRes qw( clock_gettime clock_getres clock_nanosleep
40                             ITIMER_REAL ITIMER_VIRTUAL ITIMER_PROF
41                             ITIMER_REALPROF );
42
43         $realtime   = clock_gettime(CLOCK_REALTIME);
44         $resolution = clock_getres(CLOCK_REALTIME);
45
46         clock_nanosleep(CLOCK_REALTIME, 1.5e9);
47         clock_nanosleep(CLOCK_REALTIME, time()*1e9 + 10e9, TIMER_ABSTIME);
48
49         my $ticktock = clock();
50
51         use Time::HiRes qw( stat lstat );
52
53         my @stat = stat("file");
54         my @stat = stat(FH);
55         my @stat = lstat("file");
56
57         use Time::HiRes qw( utime );
58         utime $floating_seconds, $floating_seconds, file...;
59

DESCRIPTION

61       The "Time::HiRes" module implements a Perl interface to the "usleep",
62       "nanosleep", "ualarm", "gettimeofday", and "setitimer"/"getitimer"
63       system calls, in other words, high resolution time and timers. See the
64       "EXAMPLES" section below and the test scripts for usage; see your
65       system documentation for the description of the underlying "nanosleep"
66       or "usleep", "ualarm", "gettimeofday", and "setitimer"/"getitimer"
67       calls.
68
69       If your system lacks gettimeofday() or an emulation of it you don't get
70       gettimeofday() or the one-argument form of tv_interval().  If your
71       system lacks all of nanosleep(), usleep(), select(), and "poll", you
72       don't get Time::HiRes::usleep(), Time::HiRes::nanosleep(), or
73       Time::HiRes::sleep().  If your system lacks both ualarm() and
74       setitimer() you don't get Time::HiRes::ualarm() or
75       Time::HiRes::alarm().
76
77       If you try to import an unimplemented function in the "use" statement
78       it will fail at compile time.
79
80       If your subsecond sleeping is implemented with nanosleep() instead of
81       usleep(), you can mix subsecond sleeping with signals since nanosleep()
82       does not use signals.  This, however, is not portable, and you should
83       first check for the truth value of &Time::HiRes::d_nanosleep to see
84       whether you have nanosleep, and then carefully read your nanosleep() C
85       API documentation for any peculiarities.
86
87       If you are using "nanosleep" for something else than mixing sleeping
88       with signals, give some thought to whether Perl is the tool you should
89       be using for work requiring nanosecond accuracies.
90
91       Remember that unless you are working on a hard realtime system, any
92       clocks and timers will be imprecise, especially so if you are working
93       in a pre-emptive multiuser system.  Understand the difference between
94       wallclock time and process time (in UNIX-like systems the sum of user
95       and system times).  Any attempt to sleep for X seconds will most
96       probably end up sleeping more than that, but don't be surprised if you
97       end up sleeping slightly less.
98
99       The following functions can be imported from this module.  No functions
100       are exported by default.
101
102       gettimeofday ()
103           In array context returns a two-element array with the seconds and
104           microseconds since the epoch.  In scalar context returns floating
105           seconds like Time::HiRes::time() (see below).
106
107       usleep ( $useconds )
108           Sleeps for the number of microseconds (millionths of a second)
109           specified.  Returns the number of microseconds actually slept.  Can
110           sleep for more than one second, unlike the "usleep" system call.
111           Can also sleep for zero seconds, which often works like a thread
112           yield.  See also Time::HiRes::sleep(), and clock_nanosleep().
113
114           Do not expect usleep() to be exact down to one microsecond.
115
116       nanosleep ( $nanoseconds )
117           Sleeps for the number of nanoseconds (1e9ths of a second)
118           specified.  Returns the number of nanoseconds actually slept
119           (accurate only to microseconds, the nearest thousand of them).  Can
120           sleep for more than one second.  Can also sleep for zero seconds,
121           which often works like a thread yield.  See also
122           Time::HiRes::sleep(), Time::HiRes::usleep(), and clock_nanosleep().
123
124           Do not expect nanosleep() to be exact down to one nanosecond.
125           Getting even accuracy of one thousand nanoseconds is good.
126
127       ualarm ( $useconds [, $interval_useconds ] )
128           Issues a "ualarm" call; the $interval_useconds is optional and will
129           be zero if unspecified, resulting in "alarm"-like behaviour.
130
131           Returns the remaining time in the alarm in microseconds, or "undef"
132           if an error occurred.
133
134           ualarm(0) will cancel an outstanding ualarm().
135
136           Note that the interaction between alarms and sleeps is unspecified.
137
138       tv_interval
139           tv_interval ( $ref_to_gettimeofday [, $ref_to_later_gettimeofday] )
140
141           Returns the floating seconds between the two times, which should
142           have been returned by gettimeofday(). If the second argument is
143           omitted, then the current time is used.
144
145       time ()
146           Returns a floating seconds since the epoch. This function can be
147           imported, resulting in a nice drop-in replacement for the "time"
148           provided with core Perl; see the "EXAMPLES" below.
149
150           NOTE 1: This higher resolution timer can return values either less
151           or more than the core time(), depending on whether your platform
152           rounds the higher resolution timer values up, down, or to the
153           nearest second to get the core time(), but naturally the difference
154           should be never more than half a second.  See also "clock_getres",
155           if available in your system.
156
157           NOTE 2: Since Sunday, September 9th, 2001 at 01:46:40 AM GMT, when
158           the time() seconds since epoch rolled over to 1_000_000_000, the
159           default floating point format of Perl and the seconds since epoch
160           have conspired to produce an apparent bug: if you print the value
161           of Time::HiRes::time() you seem to be getting only five decimals,
162           not six as promised (microseconds).  Not to worry, the microseconds
163           are there (assuming your platform supports such granularity in the
164           first place).  What is going on is that the default floating point
165           format of Perl only outputs 15 digits.  In this case that means ten
166           digits before the decimal separator and five after.  To see the
167           microseconds you can use either "printf"/"sprintf" with "%.6f", or
168           the gettimeofday() function in list context, which will give you
169           the seconds and microseconds as two separate values.
170
171       sleep ( $floating_seconds )
172           Sleeps for the specified amount of seconds.  Returns the number of
173           seconds actually slept (a floating point value).  This function can
174           be imported, resulting in a nice drop-in replacement for the
175           "sleep" provided with perl, see the "EXAMPLES" below.
176
177           Note that the interaction between alarms and sleeps is unspecified.
178
179       alarm ( $floating_seconds [, $interval_floating_seconds ] )
180           The "SIGALRM" signal is sent after the specified number of seconds.
181           Implemented using setitimer() if available, ualarm() if not.  The
182           $interval_floating_seconds argument is optional and will be zero if
183           unspecified, resulting in alarm()-like behaviour.  This function
184           can be imported, resulting in a nice drop-in replacement for the
185           "alarm" provided with perl, see the "EXAMPLES" below.
186
187           Returns the remaining time in the alarm in seconds, or "undef" if
188           an error occurred.
189
190           NOTE 1: With some combinations of operating systems and Perl
191           releases "SIGALRM" restarts select(), instead of interrupting it.
192           This means that an alarm() followed by a select() may together take
193           the sum of the times specified for the alarm() and the select(),
194           not just the time of the alarm().
195
196           Note that the interaction between alarms and sleeps is unspecified.
197
198       setitimer ( $which, $floating_seconds [, $interval_floating_seconds ] )
199           Start up an interval timer: after a certain time, a signal ($which)
200           arrives, and more signals may keep arriving at certain intervals.
201           To disable an "itimer", use $floating_seconds of zero.  If the
202           $interval_floating_seconds is set to zero (or unspecified), the
203           timer is disabled after the next delivered signal.
204
205           Use of interval timers may interfere with alarm(), sleep(), and
206           usleep().  In standard-speak the "interaction is unspecified",
207           which means that anything may happen: it may work, it may not.
208
209           In scalar context, the remaining time in the timer is returned.
210
211           In list context, both the remaining time and the interval are
212           returned.
213
214           There are usually three or four interval timers (signals)
215           available: the $which can be "ITIMER_REAL", "ITIMER_VIRTUAL",
216           "ITIMER_PROF", or "ITIMER_REALPROF".  Note that which ones are
217           available depends: true UNIX platforms usually have the first
218           three, but only Solaris seems to have "ITIMER_REALPROF" (which is
219           used to profile multithreaded programs).  Win32 unfortunately does
220           not have interval timers.
221
222           "ITIMER_REAL" results in alarm()-like behaviour.  Time is counted
223           in real time; that is, wallclock time.  "SIGALRM" is delivered when
224           the timer expires.
225
226           "ITIMER_VIRTUAL" counts time in (process) virtual time; that is,
227           only when the process is running.  In multiprocessor/user/CPU
228           systems this may be more or less than real or wallclock time.
229           (This time is also known as the user time.)  "SIGVTALRM" is
230           delivered when the timer expires.
231
232           "ITIMER_PROF" counts time when either the process virtual time or
233           when the operating system is running on behalf of the process (such
234           as I/O).  (This time is also known as the system time.)  (The sum
235           of user time and system time is known as the CPU time.)  "SIGPROF"
236           is delivered when the timer expires.  "SIGPROF" can interrupt
237           system calls.
238
239           The semantics of interval timers for multithreaded programs are
240           system-specific, and some systems may support additional interval
241           timers.  For example, it is unspecified which thread gets the
242           signals.  See your setitimer(2) documentation.
243
244       getitimer ( $which )
245           Return the remaining time in the interval timer specified by
246           $which.
247
248           In scalar context, the remaining time is returned.
249
250           In list context, both the remaining time and the interval are
251           returned.  The interval is always what you put in using
252           setitimer().
253
254       clock_gettime ( $which )
255           Return as seconds the current value of the POSIX high resolution
256           timer specified by $which.  All implementations that support POSIX
257           high resolution timers are supposed to support at least the $which
258           value of "CLOCK_REALTIME", which is supposed to return results
259           close to the results of "gettimeofday", or the number of seconds
260           since 00:00:00:00 January 1, 1970 Greenwich Mean Time (GMT).  Do
261           not assume that CLOCK_REALTIME is zero, it might be one, or
262           something else.  Another potentially useful (but not available
263           everywhere) value is "CLOCK_MONOTONIC", which guarantees a
264           monotonically increasing time value (unlike time() or
265           gettimeofday(), which can be adjusted).  See your system
266           documentation for other possibly supported values.
267
268       clock_getres ( $which )
269           Return as seconds the resolution of the POSIX high resolution timer
270           specified by $which.  All implementations that support POSIX high
271           resolution timers are supposed to support at least the $which value
272           of "CLOCK_REALTIME", see "clock_gettime".
273
274           NOTE: the resolution returned may be highly optimistic.  Even if
275           the resolution is high (a small number), all it means is that
276           you'll be able to specify the arguments to clock_gettime() and
277           clock_nanosleep() with that resolution.  The system might not
278           actually be able to measure events at that resolution, and the
279           various overheads and the overall system load are certain to affect
280           any timings.
281
282       clock_nanosleep ( $which, $nanoseconds, $flags = 0)
283           Sleeps for the number of nanoseconds (1e9ths of a second)
284           specified.  Returns the number of nanoseconds actually slept.  The
285           $which is the "clock id", as with clock_gettime() and
286           clock_getres().  The flags default to zero but "TIMER_ABSTIME" can
287           specified (must be exported explicitly) which means that
288           $nanoseconds is not a time interval (as is the default) but instead
289           an absolute time.  Can sleep for more than one second.  Can also
290           sleep for zero seconds, which often works like a thread yield.  See
291           also Time::HiRes::sleep(), Time::HiRes::usleep(), and
292           Time::HiRes::nanosleep().
293
294           Do not expect clock_nanosleep() to be exact down to one nanosecond.
295           Getting even accuracy of one thousand nanoseconds is good.
296
297       clock()
298           Return as seconds the process time (user + system time) spent by
299           the process since the first call to clock() (the definition is not
300           "since the start of the process", though if you are lucky these
301           times may be quite close to each other, depending on the system).
302           What this means is that you probably need to store the result of
303           your first call to clock(), and subtract that value from the
304           following results of clock().
305
306           The time returned also includes the process times of the terminated
307           child processes for which wait() has been executed.  This value is
308           somewhat like the second value returned by the times() of core
309           Perl, but not necessarily identical.  Note that due to backward
310           compatibility limitations the returned value may wrap around at
311           about 2147 seconds or at about 36 minutes.
312
313       stat
314       stat FH
315       stat EXPR
316       lstat
317       lstat FH
318       lstat EXPR
319           As "stat" in perlfunc or "lstat" in perlfunc but with the
320           access/modify/change file timestamps in subsecond resolution, if
321           the operating system and the filesystem both support such
322           timestamps.  To override the standard stat():
323
324               use Time::HiRes qw(stat);
325
326           Test for the value of &Time::HiRes::d_hires_stat to find out
327           whether the operating system supports subsecond file timestamps: a
328           value larger than zero means yes. There are unfortunately no easy
329           ways to find out whether the filesystem supports such timestamps.
330           UNIX filesystems often do; NTFS does; FAT doesn't (FAT timestamp
331           granularity is two seconds).
332
333           A zero return value of &Time::HiRes::d_hires_stat means that
334           Time::HiRes::stat is a no-op passthrough for CORE::stat() (and
335           likewise for lstat), and therefore the timestamps will stay
336           integers.  The same thing will happen if the filesystem does not do
337           subsecond timestamps, even if the &Time::HiRes::d_hires_stat is
338           non-zero.
339
340           In any case do not expect nanosecond resolution, or even a
341           microsecond resolution.  Also note that the modify/access
342           timestamps might have different resolutions, and that they need not
343           be synchronized, e.g.  if the operations are
344
345               write
346               stat # t1
347               read
348               stat # t2
349
350           the access time stamp from t2 need not be greater-than the modify
351           time stamp from t1: it may be equal or less.
352
353       utime LIST
354           As "utime" in perlfunc but with the ability to set the
355           access/modify file timestamps in subsecond resolution, if the
356           operating system and the filesystem, and the mount options of the
357           filesystem, all support such timestamps.
358
359           To override the standard utime():
360
361               use Time::HiRes qw(utime);
362
363           Test for the value of &Time::HiRes::d_hires_utime to find out
364           whether the operating system supports setting subsecond file
365           timestamps.
366
367           As with CORE::utime(), passing undef as both the atime and mtime
368           will call the syscall with a NULL argument.
369
370           The actual achievable subsecond resolution depends on the
371           combination of the operating system and the filesystem.
372
373           Modifying the timestamps may not be possible at all: for example,
374           the "noatime" filesystem mount option may prohibit you from
375           changing the access time timestamp.
376
377           Returns the number of files successfully changed.
378

EXAMPLES

380         use Time::HiRes qw(usleep ualarm gettimeofday tv_interval);
381
382         $microseconds = 750_000;
383         usleep($microseconds);
384
385         # signal alarm in 2.5s & every .1s thereafter
386         ualarm(2_500_000, 100_000);
387         # cancel that ualarm
388         ualarm(0);
389
390         # get seconds and microseconds since the epoch
391         ($s, $usec) = gettimeofday();
392
393         # measure elapsed time
394         # (could also do by subtracting 2 gettimeofday return values)
395         $t0 = [gettimeofday];
396         # do bunch of stuff here
397         $t1 = [gettimeofday];
398         # do more stuff here
399         $t0_t1 = tv_interval $t0, $t1;
400
401         $elapsed = tv_interval ($t0, [gettimeofday]);
402         $elapsed = tv_interval ($t0); # equivalent code
403
404         #
405         # replacements for time, alarm and sleep that know about
406         # floating seconds
407         #
408         use Time::HiRes;
409         $now_fractions = Time::HiRes::time;
410         Time::HiRes::sleep (2.5);
411         Time::HiRes::alarm (10.6666666);
412
413         use Time::HiRes qw ( time alarm sleep );
414         $now_fractions = time;
415         sleep (2.5);
416         alarm (10.6666666);
417
418         # Arm an interval timer to go off first at 10 seconds and
419         # after that every 2.5 seconds, in process virtual time
420
421         use Time::HiRes qw ( setitimer ITIMER_VIRTUAL time );
422
423         $SIG{VTALRM} = sub { print time, "\n" };
424         setitimer(ITIMER_VIRTUAL, 10, 2.5);
425
426         use Time::HiRes qw( clock_gettime clock_getres CLOCK_REALTIME );
427         # Read the POSIX high resolution timer.
428         my $high = clock_gettime(CLOCK_REALTIME);
429         # But how accurate we can be, really?
430         my $reso = clock_getres(CLOCK_REALTIME);
431
432         use Time::HiRes qw( clock_nanosleep TIMER_ABSTIME );
433         clock_nanosleep(CLOCK_REALTIME, 1e6);
434         clock_nanosleep(CLOCK_REALTIME, 2e9, TIMER_ABSTIME);
435
436         use Time::HiRes qw( clock );
437         my $clock0 = clock();
438         ... # Do something.
439         my $clock1 = clock();
440         my $clockd = $clock1 - $clock0;
441
442         use Time::HiRes qw( stat );
443         my ($atime, $mtime, $ctime) = (stat("istics"))[8, 9, 10];
444

C API

446       In addition to the perl API described above, a C API is available for
447       extension writers.  The following C functions are available in the
448       modglobal hash:
449
450         name             C prototype
451         ---------------  ----------------------
452         Time::NVtime     NV (*)()
453         Time::U2time     void (*)(pTHX_ UV ret[2])
454
455       Both functions return equivalent information (like "gettimeofday") but
456       with different representations.  The names "NVtime" and "U2time" were
457       selected mainly because they are operating system independent.
458       ("gettimeofday" is Unix-centric, though some platforms like Win32 and
459       VMS have emulations for it.)
460
461       Here is an example of using "NVtime" from C:
462
463         NV (*myNVtime)(); /* Returns -1 on failure. */
464         SV **svp = hv_fetchs(PL_modglobal, "Time::NVtime", 0);
465         if (!svp)         croak("Time::HiRes is required");
466         if (!SvIOK(*svp)) croak("Time::NVtime isn't a function pointer");
467         myNVtime = INT2PTR(NV(*)(), SvIV(*svp));
468         printf("The current time is: %" NVff "\n", (*myNVtime)());
469

DIAGNOSTICS

471   useconds or interval more than ...
472       In ualarm() you tried to use number of microseconds or interval (also
473       in microseconds) more than 1_000_000 and setitimer() is not available
474       in your system to emulate that case.
475
476   negative time not invented yet
477       You tried to use a negative time argument.
478
479   internal error: useconds < 0 (unsigned ... signed ...)
480       Something went horribly wrong-- the number of microseconds that cannot
481       become negative just became negative.  Maybe your compiler is broken?
482
483   useconds or uinterval equal to or more than 1000000
484       In some platforms it is not possible to get an alarm with subsecond
485       resolution and later than one second.
486
487   unimplemented in this platform
488       Some calls simply aren't available, real or emulated, on every
489       platform.
490

CAVEATS

492       Notice that the core time() maybe rounding rather than truncating.
493       What this means is that the core time() may be reporting the time as
494       one second later than gettimeofday() and Time::HiRes::time().
495
496       Adjusting the system clock (either manually or by services like ntp)
497       may cause problems, especially for long running programs that assume a
498       monotonously increasing time (note that all platforms do not adjust
499       time as gracefully as UNIX ntp does).  For example in Win32 (and
500       derived platforms like Cygwin and MinGW) the Time::HiRes::time() may
501       temporarily drift off from the system clock (and the original time())
502       by up to 0.5 seconds. Time::HiRes will notice this eventually and
503       recalibrate.  Note that since Time::HiRes 1.77 the
504       clock_gettime(CLOCK_MONOTONIC) might help in this (in case your system
505       supports CLOCK_MONOTONIC).
506
507       Some systems have APIs but not implementations: for example QNX and
508       Haiku have the interval timer APIs but not the functionality.
509
510       In pre-Sierra macOS (pre-10.12, OS X) clock_getres(), clock_gettime()
511       and clock_nanosleep() are emulated using the Mach timers; as a side
512       effect of being emulated the CLOCK_REALTIME and CLOCK_MONOTONIC are the
513       same timer.
514
515       gnukfreebsd seems to have non-functional futimens() and utimensat() (at
516       least as of 10.1): therefore the hires utime() does not work.
517

SEE ALSO

519       Perl modules BSD::Resource, Time::TAI64.
520
521       Your system documentation for clock(3), clock_gettime(2),
522       clock_getres(3), clock_nanosleep(3), clock_settime(2), getitimer(2),
523       gettimeofday(2), setitimer(2), sleep(3), stat(2), ualarm(3).
524

AUTHORS

526       D. Wegscheid <wegscd@whirlpool.com> R. Schertler <roderick@argon.org>
527       J. Hietaniemi <jhi@iki.fi> G. Aas <gisle@aas.no>
528
530       Copyright (c) 1996-2002 Douglas E. Wegscheid.  All rights reserved.
531
532       Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007, 2008 Jarkko
533       Hietaniemi.  All rights reserved.
534
535       Copyright (C) 2011, 2012, 2013 Andrew Main (Zefram) <zefram@fysh.org>
536
537       This program is free software; you can redistribute it and/or modify it
538       under the same terms as Perl itself.
539
540
541
542perl v5.36.0                      2023-01-20                          HiRes(3)
Impressum