9 our @ISA = qw(Exporter DynaLoader);
12 # More or less this same list is in Makefile.PL. Should unify.
13 our @EXPORT_OK = qw (usleep sleep ualarm alarm gettimeofday time tv_interval
14 getitimer setitimer nanosleep clock_gettime clock_getres
20 CLOCK_MONOTONIC_COARSE
22 CLOCK_MONOTONIC_PRECISE
24 CLOCK_PROCESS_CPUTIME_ID
29 CLOCK_REALTIME_PRECISE
33 CLOCK_THREAD_CPUTIME_ID
46 d_usleep d_ualarm d_gettimeofday d_getitimer d_setitimer
47 d_nanosleep d_clock_gettime d_clock_getres d_hires_utime
48 d_clock d_clock_nanosleep
52 our $VERSION = '1.9746';
53 our $XS_VERSION = $VERSION;
54 $VERSION = eval $VERSION;
59 ($constname = $AUTOLOAD) =~ s/.*:://;
60 # print "AUTOLOAD: constname = $constname ($AUTOLOAD)\n";
61 die "&Time::HiRes::constant not defined" if $constname eq 'constant';
62 my ($error, $val) = constant($constname);
63 # print "AUTOLOAD: error = $error, val = $val\n";
65 my (undef,$file,$line) = caller;
66 die "$error at $file line $line.\n";
70 *$AUTOLOAD = sub { $val };
78 if (($i eq 'clock_getres' && !&d_clock_getres) ||
79 ($i eq 'clock_gettime' && !&d_clock_gettime) ||
80 ($i eq 'clock_nanosleep' && !&d_clock_nanosleep) ||
81 ($i eq 'clock' && !&d_clock) ||
82 ($i eq 'nanosleep' && !&d_nanosleep) ||
83 ($i eq 'usleep' && !&d_usleep) ||
84 ($i eq 'utime' && !&d_hires_utime) ||
85 ($i eq 'ualarm' && !&d_ualarm)) {
87 Carp::croak("Time::HiRes::$i(): unimplemented in this platform");
90 Time::HiRes->export_to_level(1, $this, @_);
93 bootstrap Time::HiRes;
95 # Preloaded methods go here.
98 # probably could have been done in C
100 $b = [gettimeofday()] unless defined($b);
101 (${$b}[0] - ${$a}[0]) + ((${$b}[1] - ${$a}[1]) / 1_000_000);
104 # Autoload methods go after =cut, and are processed by the autosplit program.
111 Time::HiRes - High resolution alarm, sleep, gettimeofday, interval timers
115 use Time::HiRes qw( usleep ualarm gettimeofday tv_interval nanosleep
116 clock_gettime clock_getres clock_nanosleep clock
119 usleep ($microseconds);
120 nanosleep ($nanoseconds);
122 ualarm ($microseconds);
123 ualarm ($microseconds, $interval_microseconds);
125 $t0 = [gettimeofday];
126 ($seconds, $microseconds) = gettimeofday;
128 $elapsed = tv_interval ( $t0, [$seconds, $microseconds]);
129 $elapsed = tv_interval ( $t0, [gettimeofday]);
130 $elapsed = tv_interval ( $t0 );
132 use Time::HiRes qw ( time alarm sleep );
134 $now_fractions = time;
135 sleep ($floating_seconds);
136 alarm ($floating_seconds);
137 alarm ($floating_seconds, $floating_interval);
139 use Time::HiRes qw( setitimer getitimer );
141 setitimer ($which, $floating_seconds, $floating_interval );
144 use Time::HiRes qw( clock_gettime clock_getres clock_nanosleep
145 ITIMER_REAL ITIMER_VIRTUAL ITIMER_PROF
148 $realtime = clock_gettime(CLOCK_REALTIME);
149 $resolution = clock_getres(CLOCK_REALTIME);
151 clock_nanosleep(CLOCK_REALTIME, 1.5e9);
152 clock_nanosleep(CLOCK_REALTIME, time()*1e9 + 10e9, TIMER_ABSTIME);
154 my $ticktock = clock();
156 use Time::HiRes qw( stat lstat );
158 my @stat = stat("file");
160 my @stat = lstat("file");
162 use Time::HiRes qw( utime );
163 utime $floating_seconds, $floating_seconds, file...;
167 The C<Time::HiRes> module implements a Perl interface to the
168 C<usleep>, C<nanosleep>, C<ualarm>, C<gettimeofday>, and
169 C<setitimer>/C<getitimer> system calls, in other words, high
170 resolution time and timers. See the L</EXAMPLES> section below and the
171 test scripts for usage; see your system documentation for the
172 description of the underlying C<nanosleep> or C<usleep>, C<ualarm>,
173 C<gettimeofday>, and C<setitimer>/C<getitimer> calls.
175 If your system lacks C<gettimeofday()> or an emulation of it you don't
176 get C<gettimeofday()> or the one-argument form of C<tv_interval()>.
177 If your system lacks all of C<nanosleep()>, C<usleep()>,
178 C<select()>, and C<poll>, you don't get C<Time::HiRes::usleep()>,
179 C<Time::HiRes::nanosleep()>, or C<Time::HiRes::sleep()>.
180 If your system lacks both C<ualarm()> and C<setitimer()> you don't get
181 C<Time::HiRes::ualarm()> or C<Time::HiRes::alarm()>.
183 If you try to import an unimplemented function in the C<use> statement
184 it will fail at compile time.
186 If your subsecond sleeping is implemented with C<nanosleep()> instead
187 of C<usleep()>, you can mix subsecond sleeping with signals since
188 C<nanosleep()> does not use signals. This, however, is not portable,
189 and you should first check for the truth value of
190 C<&Time::HiRes::d_nanosleep> to see whether you have nanosleep, and
191 then carefully read your C<nanosleep()> C API documentation for any
194 If you are using C<nanosleep> for something else than mixing sleeping
195 with signals, give some thought to whether Perl is the tool you should
196 be using for work requiring nanosecond accuracies.
198 Remember that unless you are working on a I<hard realtime> system,
199 any clocks and timers will be imprecise, especially so if you are working
200 in a pre-emptive multiuser system. Understand the difference between
201 I<wallclock time> and process time (in UNIX-like systems the sum of
202 I<user> and I<system> times). Any attempt to sleep for X seconds will
203 most probably end up sleeping B<more> than that, but don't be surprised
204 if you end up sleeping slightly B<less>.
206 The following functions can be imported from this module.
207 No functions are exported by default.
211 =item gettimeofday ()
213 In array context returns a two-element array with the seconds and
214 microseconds since the epoch. In scalar context returns floating
215 seconds like C<Time::HiRes::time()> (see below).
217 =item usleep ( $useconds )
219 Sleeps for the number of microseconds (millionths of a second)
220 specified. Returns the number of microseconds actually slept.
221 Can sleep for more than one second, unlike the C<usleep> system call.
222 Can also sleep for zero seconds, which often works like a I<thread yield>.
223 See also C<Time::HiRes::usleep()>, C<Time::HiRes::sleep()>, and
224 C<Time::HiRes::clock_nanosleep()>.
226 Do not expect usleep() to be exact down to one microsecond.
228 =item nanosleep ( $nanoseconds )
230 Sleeps for the number of nanoseconds (1e9ths of a second) specified.
231 Returns the number of nanoseconds actually slept (accurate only to
232 microseconds, the nearest thousand of them). Can sleep for more than
233 one second. Can also sleep for zero seconds, which often works like
234 a I<thread yield>. See also C<Time::HiRes::sleep()>,
235 C<Time::HiRes::usleep()>, and C<Time::HiRes::clock_nanosleep()>.
237 Do not expect nanosleep() to be exact down to one nanosecond.
238 Getting even accuracy of one thousand nanoseconds is good.
240 =item ualarm ( $useconds [, $interval_useconds ] )
242 Issues a C<ualarm> call; the C<$interval_useconds> is optional and
243 will be zero if unspecified, resulting in C<alarm>-like behaviour.
245 Returns the remaining time in the alarm in microseconds, or C<undef>
246 if an error occurred.
248 ualarm(0) will cancel an outstanding ualarm().
250 Note that the interaction between alarms and sleeps is unspecified.
254 tv_interval ( $ref_to_gettimeofday [, $ref_to_later_gettimeofday] )
256 Returns the floating seconds between the two times, which should have
257 been returned by C<gettimeofday()>. If the second argument is omitted,
258 then the current time is used.
262 Returns a floating seconds since the epoch. This function can be
263 imported, resulting in a nice drop-in replacement for the C<time>
264 provided with core Perl; see the L</EXAMPLES> below.
266 B<NOTE 1>: This higher resolution timer can return values either less
267 or more than the core C<time()>, depending on whether your platform
268 rounds the higher resolution timer values up, down, or to the nearest second
269 to get the core C<time()>, but naturally the difference should be never
270 more than half a second. See also L</clock_getres>, if available
273 B<NOTE 2>: Since Sunday, September 9th, 2001 at 01:46:40 AM GMT, when
274 the C<time()> seconds since epoch rolled over to 1_000_000_000, the
275 default floating point format of Perl and the seconds since epoch have
276 conspired to produce an apparent bug: if you print the value of
277 C<Time::HiRes::time()> you seem to be getting only five decimals, not
278 six as promised (microseconds). Not to worry, the microseconds are
279 there (assuming your platform supports such granularity in the first
280 place). What is going on is that the default floating point format of
281 Perl only outputs 15 digits. In this case that means ten digits
282 before the decimal separator and five after. To see the microseconds
283 you can use either C<printf>/C<sprintf> with C<"%.6f">, or the
284 C<gettimeofday()> function in list context, which will give you the
285 seconds and microseconds as two separate values.
287 =item sleep ( $floating_seconds )
289 Sleeps for the specified amount of seconds. Returns the number of
290 seconds actually slept (a floating point value). This function can
291 be imported, resulting in a nice drop-in replacement for the C<sleep>
292 provided with perl, see the L</EXAMPLES> below.
294 Note that the interaction between alarms and sleeps is unspecified.
296 =item alarm ( $floating_seconds [, $interval_floating_seconds ] )
298 The C<SIGALRM> signal is sent after the specified number of seconds.
299 Implemented using C<setitimer()> if available, C<ualarm()> if not.
300 The C<$interval_floating_seconds> argument is optional and will be
301 zero if unspecified, resulting in C<alarm()>-like behaviour. This
302 function can be imported, resulting in a nice drop-in replacement for
303 the C<alarm> provided with perl, see the L</EXAMPLES> below.
305 Returns the remaining time in the alarm in seconds, or C<undef>
306 if an error occurred.
308 B<NOTE 1>: With some combinations of operating systems and Perl
309 releases C<SIGALRM> restarts C<select()>, instead of interrupting it.
310 This means that an C<alarm()> followed by a C<select()> may together
311 take the sum of the times specified for the C<alarm()> and the
312 C<select()>, not just the time of the C<alarm()>.
314 Note that the interaction between alarms and sleeps is unspecified.
316 =item setitimer ( $which, $floating_seconds [, $interval_floating_seconds ] )
318 Start up an interval timer: after a certain time, a signal ($which) arrives,
319 and more signals may keep arriving at certain intervals. To disable
320 an "itimer", use C<$floating_seconds> of zero. If the
321 C<$interval_floating_seconds> is set to zero (or unspecified), the
322 timer is disabled B<after> the next delivered signal.
324 Use of interval timers may interfere with C<alarm()>, C<sleep()>,
325 and C<usleep()>. In standard-speak the "interaction is unspecified",
326 which means that I<anything> may happen: it may work, it may not.
328 In scalar context, the remaining time in the timer is returned.
330 In list context, both the remaining time and the interval are returned.
332 There are usually three or four interval timers (signals) available: the
333 C<$which> can be C<ITIMER_REAL>, C<ITIMER_VIRTUAL>, C<ITIMER_PROF>, or
334 C<ITIMER_REALPROF>. Note that which ones are available depends: true
335 UNIX platforms usually have the first three, but only Solaris seems to
336 have C<ITIMER_REALPROF> (which is used to profile multithreaded programs).
337 Win32 unfortunately does not have interval timers.
339 C<ITIMER_REAL> results in C<alarm()>-like behaviour. Time is counted in
340 I<real time>; that is, wallclock time. C<SIGALRM> is delivered when
343 C<ITIMER_VIRTUAL> counts time in (process) I<virtual time>; that is,
344 only when the process is running. In multiprocessor/user/CPU systems
345 this may be more or less than real or wallclock time. (This time is
346 also known as the I<user time>.) C<SIGVTALRM> is delivered when the
349 C<ITIMER_PROF> counts time when either the process virtual time or when
350 the operating system is running on behalf of the process (such as I/O).
351 (This time is also known as the I<system time>.) (The sum of user
352 time and system time is known as the I<CPU time>.) C<SIGPROF> is
353 delivered when the timer expires. C<SIGPROF> can interrupt system calls.
355 The semantics of interval timers for multithreaded programs are
356 system-specific, and some systems may support additional interval
357 timers. For example, it is unspecified which thread gets the signals.
358 See your C<setitimer()> documentation.
360 =item getitimer ( $which )
362 Return the remaining time in the interval timer specified by C<$which>.
364 In scalar context, the remaining time is returned.
366 In list context, both the remaining time and the interval are returned.
367 The interval is always what you put in using C<setitimer()>.
369 =item clock_gettime ( $which )
371 Return as seconds the current value of the POSIX high resolution timer
372 specified by C<$which>. All implementations that support POSIX high
373 resolution timers are supposed to support at least the C<$which> value
374 of C<CLOCK_REALTIME>, which is supposed to return results close to the
375 results of C<gettimeofday>, or the number of seconds since 00:00:00:00
376 January 1, 1970 Greenwich Mean Time (GMT). Do not assume that
377 CLOCK_REALTIME is zero, it might be one, or something else.
378 Another potentially useful (but not available everywhere) value is
379 C<CLOCK_MONOTONIC>, which guarantees a monotonically increasing time
380 value (unlike time() or gettimeofday(), which can be adjusted).
381 See your system documentation for other possibly supported values.
383 =item clock_getres ( $which )
385 Return as seconds the resolution of the POSIX high resolution timer
386 specified by C<$which>. All implementations that support POSIX high
387 resolution timers are supposed to support at least the C<$which> value
388 of C<CLOCK_REALTIME>, see L</clock_gettime>.
390 B<NOTE>: the resolution returned may be highly optimistic. Even if
391 the resolution is high (a small number), all it means is that you'll
392 be able to specify the arguments to clock_gettime() and clock_nanosleep()
393 with that resolution. The system might not actually be able to measure
394 events at that resolution, and the various overheads and the overall system
395 load are certain to affect any timings.
397 =item clock_nanosleep ( $which, $nanoseconds, $flags = 0)
399 Sleeps for the number of nanoseconds (1e9ths of a second) specified.
400 Returns the number of nanoseconds actually slept. The $which is the
401 "clock id", as with clock_gettime() and clock_getres(). The flags
402 default to zero but C<TIMER_ABSTIME> can specified (must be exported
403 explicitly) which means that C<$nanoseconds> is not a time interval
404 (as is the default) but instead an absolute time. Can sleep for more
405 than one second. Can also sleep for zero seconds, which often works
406 like a I<thread yield>. See also C<Time::HiRes::sleep()>,
407 C<Time::HiRes::usleep()>, and C<Time::HiRes::nanosleep()>.
409 Do not expect clock_nanosleep() to be exact down to one nanosecond.
410 Getting even accuracy of one thousand nanoseconds is good.
414 Return as seconds the I<process time> (user + system time) spent by
415 the process since the first call to clock() (the definition is B<not>
416 "since the start of the process", though if you are lucky these times
417 may be quite close to each other, depending on the system). What this
418 means is that you probably need to store the result of your first call
419 to clock(), and subtract that value from the following results of clock().
421 The time returned also includes the process times of the terminated
422 child processes for which wait() has been executed. This value is
423 somewhat like the second value returned by the times() of core Perl,
424 but not necessarily identical. Note that due to backward
425 compatibility limitations the returned value may wrap around at about
426 2147 seconds or at about 36 minutes.
440 As L<perlfunc/stat> or L<perlfunc/lstat>
441 but with the access/modify/change file timestamps
442 in subsecond resolution, if the operating system and the filesystem
443 both support such timestamps. To override the standard stat():
445 use Time::HiRes qw(stat);
447 Test for the value of &Time::HiRes::d_hires_stat to find out whether
448 the operating system supports subsecond file timestamps: a value
449 larger than zero means yes. There are unfortunately no easy
450 ways to find out whether the filesystem supports such timestamps.
451 UNIX filesystems often do; NTFS does; FAT doesn't (FAT timestamp
452 granularity is B<two> seconds).
454 A zero return value of &Time::HiRes::d_hires_stat means that
455 Time::HiRes::stat is a no-op passthrough for CORE::stat()
456 (and likewise for lstat),
457 and therefore the timestamps will stay integers. The same
458 thing will happen if the filesystem does not do subsecond timestamps,
459 even if the &Time::HiRes::d_hires_stat is non-zero.
461 In any case do not expect nanosecond resolution, or even a microsecond
462 resolution. Also note that the modify/access timestamps might have
463 different resolutions, and that they need not be synchronized, e.g.
464 if the operations are
471 the access time stamp from t2 need not be greater-than the modify
472 time stamp from t1: it may be equal or I<less>.
477 but with the ability to set the access/modify file timestamps
478 in subsecond resolution, if the operating system and the filesystem
479 both support such timestamps. To override the standard utime():
481 use Time::HiRes qw(utime);
483 Test for the value of &Time::HiRes::d_hires_utime to find out whether
484 the operating system supports setting subsecond file timestamps.
486 As with CORE::utime(), passing undef as both the atime and mtime will
487 call the syscall with a NULL argument.
489 The actual achievable subsecond resolution depends on the combination
490 of the operating system and the filesystem.
492 Returns the number of files successfully changed.
498 use Time::HiRes qw(usleep ualarm gettimeofday tv_interval);
500 $microseconds = 750_000;
501 usleep($microseconds);
503 # signal alarm in 2.5s & every .1s thereafter
504 ualarm(2_500_000, 100_000);
508 # get seconds and microseconds since the epoch
509 ($s, $usec) = gettimeofday();
511 # measure elapsed time
512 # (could also do by subtracting 2 gettimeofday return values)
513 $t0 = [gettimeofday];
514 # do bunch of stuff here
515 $t1 = [gettimeofday];
517 $t0_t1 = tv_interval $t0, $t1;
519 $elapsed = tv_interval ($t0, [gettimeofday]);
520 $elapsed = tv_interval ($t0); # equivalent code
523 # replacements for time, alarm and sleep that know about
527 $now_fractions = Time::HiRes::time;
528 Time::HiRes::sleep (2.5);
529 Time::HiRes::alarm (10.6666666);
531 use Time::HiRes qw ( time alarm sleep );
532 $now_fractions = time;
536 # Arm an interval timer to go off first at 10 seconds and
537 # after that every 2.5 seconds, in process virtual time
539 use Time::HiRes qw ( setitimer ITIMER_VIRTUAL time );
541 $SIG{VTALRM} = sub { print time, "\n" };
542 setitimer(ITIMER_VIRTUAL, 10, 2.5);
544 use Time::HiRes qw( clock_gettime clock_getres CLOCK_REALTIME );
545 # Read the POSIX high resolution timer.
546 my $high = clock_gettime(CLOCK_REALTIME);
547 # But how accurate we can be, really?
548 my $reso = clock_getres(CLOCK_REALTIME);
550 use Time::HiRes qw( clock_nanosleep TIMER_ABSTIME );
551 clock_nanosleep(CLOCK_REALTIME, 1e6);
552 clock_nanosleep(CLOCK_REALTIME, 2e9, TIMER_ABSTIME);
554 use Time::HiRes qw( clock );
555 my $clock0 = clock();
557 my $clock1 = clock();
558 my $clockd = $clock1 - $clock0;
560 use Time::HiRes qw( stat );
561 my ($atime, $mtime, $ctime) = (stat("istics"))[8, 9, 10];
565 In addition to the perl API described above, a C API is available for
566 extension writers. The following C functions are available in the
570 --------------- ----------------------
571 Time::NVtime NV (*)()
572 Time::U2time void (*)(pTHX_ UV ret[2])
574 Both functions return equivalent information (like C<gettimeofday>)
575 but with different representations. The names C<NVtime> and C<U2time>
576 were selected mainly because they are operating system independent.
577 (C<gettimeofday> is Unix-centric, though some platforms like Win32 and
578 VMS have emulations for it.)
580 Here is an example of using C<NVtime> from C:
582 NV (*myNVtime)(); /* Returns -1 on failure. */
583 SV **svp = hv_fetchs(PL_modglobal, "Time::NVtime", 0);
584 if (!svp) croak("Time::HiRes is required");
585 if (!SvIOK(*svp)) croak("Time::NVtime isn't a function pointer");
586 myNVtime = INT2PTR(NV(*)(), SvIV(*svp));
587 printf("The current time is: %" NVff "\n", (*myNVtime)());
591 =head2 useconds or interval more than ...
593 In ualarm() you tried to use number of microseconds or interval (also
594 in microseconds) more than 1_000_000 and setitimer() is not available
595 in your system to emulate that case.
597 =head2 negative time not invented yet
599 You tried to use a negative time argument.
601 =head2 internal error: useconds < 0 (unsigned ... signed ...)
603 Something went horribly wrong-- the number of microseconds that cannot
604 become negative just became negative. Maybe your compiler is broken?
606 =head2 useconds or uinterval equal to or more than 1000000
608 In some platforms it is not possible to get an alarm with subsecond
609 resolution and later than one second.
611 =head2 unimplemented in this platform
613 Some calls simply aren't available, real or emulated, on every platform.
617 Notice that the core C<time()> maybe rounding rather than truncating.
618 What this means is that the core C<time()> may be reporting the time
619 as one second later than C<gettimeofday()> and C<Time::HiRes::time()>.
621 Adjusting the system clock (either manually or by services like ntp)
622 may cause problems, especially for long running programs that assume
623 a monotonously increasing time (note that all platforms do not adjust
624 time as gracefully as UNIX ntp does). For example in Win32 (and derived
625 platforms like Cygwin and MinGW) the Time::HiRes::time() may temporarily
626 drift off from the system clock (and the original time()) by up to 0.5
627 seconds. Time::HiRes will notice this eventually and recalibrate.
628 Note that since Time::HiRes 1.77 the clock_gettime(CLOCK_MONOTONIC)
629 might help in this (in case your system supports CLOCK_MONOTONIC).
631 Some systems have APIs but not implementations: for example QNX and Haiku
632 have the interval timer APIs but not the functionality.
634 In pre-Sierra macOS (pre-10.12, OS X) clock_getres(), clock_gettime()
635 and clock_nanosleep() are emulated using the Mach timers; as a side
636 effect of being emulated the CLOCK_REALTIME and CLOCK_MONOTONIC are
639 gnukfreebsd seems to have non-functional futimens() and utimensat()
640 (at least as of 10.1): therefore the hires utime() does not work.
644 Perl modules L<BSD::Resource>, L<Time::TAI64>.
646 Your system documentation for C<clock>, C<clock_gettime>,
647 C<clock_getres>, C<clock_nanosleep>, C<clock_settime>, C<getitimer>,
648 C<gettimeofday>, C<setitimer>, C<sleep>, C<stat>, C<ualarm>.
652 D. Wegscheid <wegscd@whirlpool.com>
653 R. Schertler <roderick@argon.org>
654 J. Hietaniemi <jhi@iki.fi>
655 G. Aas <gisle@aas.no>
657 =head1 COPYRIGHT AND LICENSE
659 Copyright (c) 1996-2002 Douglas E. Wegscheid. All rights reserved.
661 Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007, 2008 Jarkko Hietaniemi.
664 Copyright (C) 2011, 2012, 2013 Andrew Main (Zefram) <zefram@fysh.org>
666 This program is free software; you can redistribute it and/or modify
667 it under the same terms as Perl itself.