1HiRes(3) User Contributed Perl Documentation HiRes(3)
2
3
4
6 Time::HiRes - High resolution alarm, sleep, gettimeofday, interval
7 timers
8
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
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
70 get "gettimeofday()" or the one-argument form of "tv_interval()". If
71 your system lacks all of "nanosleep()", "usleep()", "select()", and
72 "poll", you don't get "Time::HiRes::usleep()",
73 "Time::HiRes::nanosleep()", or "Time::HiRes::sleep()". If your system
74 lacks both "ualarm()" and "setitimer()" you don't get
75 "Time::HiRes::ualarm()" or "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
82 "nanosleep()" does not use signals. This, however, is not portable,
83 and you should first check for the truth value of
84 &Time::HiRes::d_nanosleep to see whether you have nanosleep, and then
85 carefully read your "nanosleep()" C API documentation for any
86 peculiarities.
87
88 If you are using "nanosleep" for something else than mixing sleeping
89 with signals, give some thought to whether Perl is the tool you should
90 be using for work requiring nanosecond accuracies.
91
92 Remember that unless you are working on a hard realtime system, any
93 clocks and timers will be imprecise, especially so if you are working
94 in a pre-emptive multiuser system. Understand the difference between
95 wallclock time and process time (in UNIX-like systems the sum of user
96 and system times). Any attempt to sleep for X seconds will most
97 probably end up sleeping more than that, but don't be surprised if you
98 end up sleeping slightly less.
99
100 The following functions can be imported from this module. No functions
101 are exported by default.
102
103 gettimeofday ()
104 In array context returns a two-element array with the seconds and
105 microseconds since the epoch. In scalar context returns floating
106 seconds like "Time::HiRes::time()" (see below).
107
108 usleep ( $useconds )
109 Sleeps for the number of microseconds (millionths of a second)
110 specified. Returns the number of microseconds actually slept. Can
111 sleep for more than one second, unlike the "usleep" system call.
112 Can also sleep for zero seconds, which often works like a thread
113 yield. See also "Time::HiRes::sleep()", and "clock_nanosleep()".
114
115 Do not expect usleep() to be exact down to one microsecond.
116
117 nanosleep ( $nanoseconds )
118 Sleeps for the number of nanoseconds (1e9ths of a second)
119 specified. Returns the number of nanoseconds actually slept
120 (accurate only to microseconds, the nearest thousand of them). Can
121 sleep for more than one second. Can also sleep for zero seconds,
122 which often works like a thread yield. See also
123 "Time::HiRes::sleep()", "Time::HiRes::usleep()", and
124 "clock_nanosleep()".
125
126 Do not expect nanosleep() to be exact down to one nanosecond.
127 Getting even accuracy of one thousand nanoseconds is good.
128
129 ualarm ( $useconds [, $interval_useconds ] )
130 Issues a "ualarm" call; the $interval_useconds is optional and will
131 be zero if unspecified, resulting in "alarm"-like behaviour.
132
133 Returns the remaining time in the alarm in microseconds, or "undef"
134 if an error occurred.
135
136 ualarm(0) will cancel an outstanding ualarm().
137
138 Note that the interaction between alarms and sleeps is unspecified.
139
140 tv_interval
141 tv_interval ( $ref_to_gettimeofday [, $ref_to_later_gettimeofday] )
142
143 Returns the floating seconds between the two times, which should
144 have been returned by "gettimeofday()". If the second argument is
145 omitted, then the current time is used.
146
147 time ()
148 Returns a floating seconds since the epoch. This function can be
149 imported, resulting in a nice drop-in replacement for the "time"
150 provided with core Perl; see the "EXAMPLES" below.
151
152 NOTE 1: This higher resolution timer can return values either less
153 or more than the core "time()", depending on whether your platform
154 rounds the higher resolution timer values up, down, or to the
155 nearest second to get the core "time()", but naturally the
156 difference should be never more than half a second. See also
157 "clock_getres", if available in your system.
158
159 NOTE 2: Since Sunday, September 9th, 2001 at 01:46:40 AM GMT, when
160 the "time()" seconds since epoch rolled over to 1_000_000_000, the
161 default floating point format of Perl and the seconds since epoch
162 have conspired to produce an apparent bug: if you print the value
163 of "Time::HiRes::time()" you seem to be getting only five decimals,
164 not six as promised (microseconds). Not to worry, the microseconds
165 are there (assuming your platform supports such granularity in the
166 first place). What is going on is that the default floating point
167 format of Perl only outputs 15 digits. In this case that means ten
168 digits before the decimal separator and five after. To see the
169 microseconds you can use either "printf"/"sprintf" with "%.6f", or
170 the "gettimeofday()" function in list context, which will give you
171 the seconds and microseconds as two separate values.
172
173 sleep ( $floating_seconds )
174 Sleeps for the specified amount of seconds. Returns the number of
175 seconds actually slept (a floating point value). This function can
176 be imported, resulting in a nice drop-in replacement for the
177 "sleep" provided with perl, see the "EXAMPLES" below.
178
179 Note that the interaction between alarms and sleeps is unspecified.
180
181 alarm ( $floating_seconds [, $interval_floating_seconds ] )
182 The "SIGALRM" signal is sent after the specified number of seconds.
183 Implemented using "setitimer()" if available, "ualarm()" if not.
184 The $interval_floating_seconds argument is optional and will be
185 zero if unspecified, resulting in "alarm()"-like behaviour. This
186 function can be imported, resulting in a nice drop-in replacement
187 for the "alarm" provided with perl, see the "EXAMPLES" below.
188
189 Returns the remaining time in the alarm in seconds, or "undef" if
190 an error occurred.
191
192 NOTE 1: With some combinations of operating systems and Perl
193 releases "SIGALRM" restarts "select()", instead of interrupting it.
194 This means that an "alarm()" followed by a "select()" may together
195 take the sum of the times specified for the "alarm()" and the
196 "select()", not just the time of the "alarm()".
197
198 Note that the interaction between alarms and sleeps is unspecified.
199
200 setitimer ( $which, $floating_seconds [, $interval_floating_seconds ] )
201 Start up an interval timer: after a certain time, a signal ($which)
202 arrives, and more signals may keep arriving at certain intervals.
203 To disable an "itimer", use $floating_seconds of zero. If the
204 $interval_floating_seconds is set to zero (or unspecified), the
205 timer is disabled after the next delivered signal.
206
207 Use of interval timers may interfere with "alarm()", "sleep()", and
208 "usleep()". In standard-speak the "interaction is unspecified",
209 which means that anything may happen: it may work, it may not.
210
211 In scalar context, the remaining time in the timer is returned.
212
213 In list context, both the remaining time and the interval are
214 returned.
215
216 There are usually three or four interval timers (signals)
217 available: the $which can be "ITIMER_REAL", "ITIMER_VIRTUAL",
218 "ITIMER_PROF", or "ITIMER_REALPROF". Note that which ones are
219 available depends: true UNIX platforms usually have the first
220 three, but only Solaris seems to have "ITIMER_REALPROF" (which is
221 used to profile multithreaded programs). Win32 unfortunately does
222 not have interval timers.
223
224 "ITIMER_REAL" results in "alarm()"-like behaviour. Time is counted
225 in real time; that is, wallclock time. "SIGALRM" is delivered when
226 the timer expires.
227
228 "ITIMER_VIRTUAL" counts time in (process) virtual time; that is,
229 only when the process is running. In multiprocessor/user/CPU
230 systems this may be more or less than real or wallclock time.
231 (This time is also known as the user time.) "SIGVTALRM" is
232 delivered when the timer expires.
233
234 "ITIMER_PROF" counts time when either the process virtual time or
235 when the operating system is running on behalf of the process (such
236 as I/O). (This time is also known as the system time.) (The sum
237 of user time and system time is known as the CPU time.) "SIGPROF"
238 is delivered when the timer expires. "SIGPROF" can interrupt
239 system calls.
240
241 The semantics of interval timers for multithreaded programs are
242 system-specific, and some systems may support additional interval
243 timers. For example, it is unspecified which thread gets the
244 signals. See your setitimer(2) documentation.
245
246 getitimer ( $which )
247 Return the remaining time in the interval timer specified by
248 $which.
249
250 In scalar context, the remaining time is returned.
251
252 In list context, both the remaining time and the interval are
253 returned. The interval is always what you put in using
254 "setitimer()".
255
256 clock_gettime ( $which )
257 Return as seconds the current value of the POSIX high resolution
258 timer specified by $which. All implementations that support POSIX
259 high resolution timers are supposed to support at least the $which
260 value of "CLOCK_REALTIME", which is supposed to return results
261 close to the results of "gettimeofday", or the number of seconds
262 since 00:00:00:00 January 1, 1970 Greenwich Mean Time (GMT). Do
263 not assume that CLOCK_REALTIME is zero, it might be one, or
264 something else. Another potentially useful (but not available
265 everywhere) value is "CLOCK_MONOTONIC", which guarantees a
266 monotonically increasing time value (unlike time() or
267 gettimeofday(), which can be adjusted). See your system
268 documentation for other possibly supported values.
269
270 clock_getres ( $which )
271 Return as seconds the resolution of the POSIX high resolution timer
272 specified by $which. All implementations that support POSIX high
273 resolution timers are supposed to support at least the $which value
274 of "CLOCK_REALTIME", see "clock_gettime".
275
276 NOTE: the resolution returned may be highly optimistic. Even if
277 the resolution is high (a small number), all it means is that
278 you'll be able to specify the arguments to clock_gettime() and
279 clock_nanosleep() with that resolution. The system might not
280 actually be able to measure events at that resolution, and the
281 various overheads and the overall system load are certain to affect
282 any timings.
283
284 clock_nanosleep ( $which, $nanoseconds, $flags = 0)
285 Sleeps for the number of nanoseconds (1e9ths of a second)
286 specified. Returns the number of nanoseconds actually slept. The
287 $which is the "clock id", as with clock_gettime() and
288 clock_getres(). The flags default to zero but "TIMER_ABSTIME" can
289 specified (must be exported explicitly) which means that
290 $nanoseconds is not a time interval (as is the default) but instead
291 an absolute time. Can sleep for more than one second. Can also
292 sleep for zero seconds, which often works like a thread yield. See
293 also "Time::HiRes::sleep()", "Time::HiRes::usleep()", and
294 "Time::HiRes::nanosleep()".
295
296 Do not expect clock_nanosleep() to be exact down to one nanosecond.
297 Getting even accuracy of one thousand nanoseconds is good.
298
299 clock()
300 Return as seconds the process time (user + system time) spent by
301 the process since the first call to clock() (the definition is not
302 "since the start of the process", though if you are lucky these
303 times may be quite close to each other, depending on the system).
304 What this means is that you probably need to store the result of
305 your first call to clock(), and subtract that value from the
306 following results of clock().
307
308 The time returned also includes the process times of the terminated
309 child processes for which wait() has been executed. This value is
310 somewhat like the second value returned by the times() of core
311 Perl, but not necessarily identical. Note that due to backward
312 compatibility limitations the returned value may wrap around at
313 about 2147 seconds or at about 36 minutes.
314
315 stat
316 stat FH
317 stat EXPR
318 lstat
319 lstat FH
320 lstat EXPR
321 As "stat" in perlfunc or "lstat" in perlfunc but with the
322 access/modify/change file timestamps in subsecond resolution, if
323 the operating system and the filesystem both support such
324 timestamps. To override the standard stat():
325
326 use Time::HiRes qw(stat);
327
328 Test for the value of &Time::HiRes::d_hires_stat to find out
329 whether the operating system supports subsecond file timestamps: a
330 value larger than zero means yes. There are unfortunately no easy
331 ways to find out whether the filesystem supports such timestamps.
332 UNIX filesystems often do; NTFS does; FAT doesn't (FAT timestamp
333 granularity is two seconds).
334
335 A zero return value of &Time::HiRes::d_hires_stat means that
336 Time::HiRes::stat is a no-op passthrough for CORE::stat() (and
337 likewise for lstat), and therefore the timestamps will stay
338 integers. The same thing will happen if the filesystem does not do
339 subsecond timestamps, even if the &Time::HiRes::d_hires_stat is
340 non-zero.
341
342 In any case do not expect nanosecond resolution, or even a
343 microsecond resolution. Also note that the modify/access
344 timestamps might have different resolutions, and that they need not
345 be synchronized, e.g. if the operations are
346
347 write
348 stat # t1
349 read
350 stat # t2
351
352 the access time stamp from t2 need not be greater-than the modify
353 time stamp from t1: it may be equal or less.
354
355 utime LIST
356 As "utime" in perlfunc but with the ability to set the
357 access/modify file timestamps in subsecond resolution, if the
358 operating system and the filesystem, and the mount options of the
359 filesystem, all support such timestamps.
360
361 To override the standard utime():
362
363 use Time::HiRes qw(utime);
364
365 Test for the value of &Time::HiRes::d_hires_utime to find out
366 whether the operating system supports setting subsecond file
367 timestamps.
368
369 As with CORE::utime(), passing undef as both the atime and mtime
370 will call the syscall with a NULL argument.
371
372 The actual achievable subsecond resolution depends on the
373 combination of the operating system and the filesystem.
374
375 Modifying the timestamps may not be possible at all: for example,
376 the "noatime" filesystem mount option may prohibit you from
377 changing the access time timestamp.
378
379 Returns the number of files successfully changed.
380
382 use Time::HiRes qw(usleep ualarm gettimeofday tv_interval);
383
384 $microseconds = 750_000;
385 usleep($microseconds);
386
387 # signal alarm in 2.5s & every .1s thereafter
388 ualarm(2_500_000, 100_000);
389 # cancel that ualarm
390 ualarm(0);
391
392 # get seconds and microseconds since the epoch
393 ($s, $usec) = gettimeofday();
394
395 # measure elapsed time
396 # (could also do by subtracting 2 gettimeofday return values)
397 $t0 = [gettimeofday];
398 # do bunch of stuff here
399 $t1 = [gettimeofday];
400 # do more stuff here
401 $t0_t1 = tv_interval $t0, $t1;
402
403 $elapsed = tv_interval ($t0, [gettimeofday]);
404 $elapsed = tv_interval ($t0); # equivalent code
405
406 #
407 # replacements for time, alarm and sleep that know about
408 # floating seconds
409 #
410 use Time::HiRes;
411 $now_fractions = Time::HiRes::time;
412 Time::HiRes::sleep (2.5);
413 Time::HiRes::alarm (10.6666666);
414
415 use Time::HiRes qw ( time alarm sleep );
416 $now_fractions = time;
417 sleep (2.5);
418 alarm (10.6666666);
419
420 # Arm an interval timer to go off first at 10 seconds and
421 # after that every 2.5 seconds, in process virtual time
422
423 use Time::HiRes qw ( setitimer ITIMER_VIRTUAL time );
424
425 $SIG{VTALRM} = sub { print time, "\n" };
426 setitimer(ITIMER_VIRTUAL, 10, 2.5);
427
428 use Time::HiRes qw( clock_gettime clock_getres CLOCK_REALTIME );
429 # Read the POSIX high resolution timer.
430 my $high = clock_gettime(CLOCK_REALTIME);
431 # But how accurate we can be, really?
432 my $reso = clock_getres(CLOCK_REALTIME);
433
434 use Time::HiRes qw( clock_nanosleep TIMER_ABSTIME );
435 clock_nanosleep(CLOCK_REALTIME, 1e6);
436 clock_nanosleep(CLOCK_REALTIME, 2e9, TIMER_ABSTIME);
437
438 use Time::HiRes qw( clock );
439 my $clock0 = clock();
440 ... # Do something.
441 my $clock1 = clock();
442 my $clockd = $clock1 - $clock0;
443
444 use Time::HiRes qw( stat );
445 my ($atime, $mtime, $ctime) = (stat("istics"))[8, 9, 10];
446
448 In addition to the perl API described above, a C API is available for
449 extension writers. The following C functions are available in the
450 modglobal hash:
451
452 name C prototype
453 --------------- ----------------------
454 Time::NVtime NV (*)()
455 Time::U2time void (*)(pTHX_ UV ret[2])
456
457 Both functions return equivalent information (like "gettimeofday") but
458 with different representations. The names "NVtime" and "U2time" were
459 selected mainly because they are operating system independent.
460 ("gettimeofday" is Unix-centric, though some platforms like Win32 and
461 VMS have emulations for it.)
462
463 Here is an example of using "NVtime" from C:
464
465 NV (*myNVtime)(); /* Returns -1 on failure. */
466 SV **svp = hv_fetchs(PL_modglobal, "Time::NVtime", 0);
467 if (!svp) croak("Time::HiRes is required");
468 if (!SvIOK(*svp)) croak("Time::NVtime isn't a function pointer");
469 myNVtime = INT2PTR(NV(*)(), SvIV(*svp));
470 printf("The current time is: %" NVff "\n", (*myNVtime)());
471
473 useconds or interval more than ...
474 In ualarm() you tried to use number of microseconds or interval (also
475 in microseconds) more than 1_000_000 and setitimer() is not available
476 in your system to emulate that case.
477
478 negative time not invented yet
479 You tried to use a negative time argument.
480
481 internal error: useconds < 0 (unsigned ... signed ...)
482 Something went horribly wrong-- the number of microseconds that cannot
483 become negative just became negative. Maybe your compiler is broken?
484
485 useconds or uinterval equal to or more than 1000000
486 In some platforms it is not possible to get an alarm with subsecond
487 resolution and later than one second.
488
489 unimplemented in this platform
490 Some calls simply aren't available, real or emulated, on every
491 platform.
492
494 Notice that the core "time()" maybe rounding rather than truncating.
495 What this means is that the core "time()" may be reporting the time as
496 one second later than "gettimeofday()" and "Time::HiRes::time()".
497
498 Adjusting the system clock (either manually or by services like ntp)
499 may cause problems, especially for long running programs that assume a
500 monotonously increasing time (note that all platforms do not adjust
501 time as gracefully as UNIX ntp does). For example in Win32 (and
502 derived platforms like Cygwin and MinGW) the Time::HiRes::time() may
503 temporarily drift off from the system clock (and the original time())
504 by up to 0.5 seconds. Time::HiRes will notice this eventually and
505 recalibrate. Note that since Time::HiRes 1.77 the
506 clock_gettime(CLOCK_MONOTONIC) might help in this (in case your system
507 supports CLOCK_MONOTONIC).
508
509 Some systems have APIs but not implementations: for example QNX and
510 Haiku have the interval timer APIs but not the functionality.
511
512 In pre-Sierra macOS (pre-10.12, OS X) clock_getres(), clock_gettime()
513 and clock_nanosleep() are emulated using the Mach timers; as a side
514 effect of being emulated the CLOCK_REALTIME and CLOCK_MONOTONIC are the
515 same timer.
516
517 gnukfreebsd seems to have non-functional futimens() and utimensat() (at
518 least as of 10.1): therefore the hires utime() does not work.
519
521 Perl modules BSD::Resource, Time::TAI64.
522
523 Your system documentation for clock(3), clock_gettime(2),
524 clock_getres(3), clock_nanosleep(3), clock_settime(2), getitimer(2),
525 gettimeofday(2), setitimer(2), sleep(3), stat(2), ualarm(3).
526
528 D. Wegscheid <wegscd@whirlpool.com> R. Schertler <roderick@argon.org>
529 J. Hietaniemi <jhi@iki.fi> G. Aas <gisle@aas.no>
530
532 Copyright (c) 1996-2002 Douglas E. Wegscheid. All rights reserved.
533
534 Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007, 2008 Jarkko
535 Hietaniemi. All rights reserved.
536
537 Copyright (C) 2011, 2012, 2013 Andrew Main (Zefram) <zefram@fysh.org>
538
539 This program is free software; you can redistribute it and/or modify it
540 under the same terms as Perl itself.
541
542
543
544perl v5.36.0 2022-07-22 HiRes(3)