9 our @ISA = qw(Exporter DynaLoader);
12 our @EXPORT_OK = qw (usleep sleep ualarm alarm gettimeofday time tv_interval
13 getitimer setitimer nanosleep clock_gettime clock_getres
15 CLOCK_BOOTTIME CLOCK_HIGHRES
16 CLOCK_MONOTONIC CLOCK_MONOTONIC_COARSE
17 CLOCK_MONOTONIC_PRECISE CLOCK_MONOTONIC_RAW
18 CLOCK_PROCESS_CPUTIME_ID
19 CLOCK_REALTIME CLOCK_REALTIME_COARSE
20 CLOCK_REALTIME_FAST CLOCK_REALTIME_PRECISE
21 CLOCK_SECOND CLOCK_SOFTTIME CLOCK_THREAD_CPUTIME_ID
22 CLOCK_TIMEOFDAY CLOCKS_PER_SEC
23 ITIMER_REAL ITIMER_VIRTUAL ITIMER_PROF ITIMER_REALPROF
25 d_usleep d_ualarm d_gettimeofday d_getitimer d_setitimer
26 d_nanosleep d_clock_gettime d_clock_getres
27 d_clock d_clock_nanosleep
31 our $VERSION = '1.9728';
32 our $XS_VERSION = $VERSION;
33 $VERSION = eval $VERSION;
38 ($constname = $AUTOLOAD) =~ s/.*:://;
39 # print "AUTOLOAD: constname = $constname ($AUTOLOAD)\n";
40 die "&Time::HiRes::constant not defined" if $constname eq 'constant';
41 my ($error, $val) = constant($constname);
42 # print "AUTOLOAD: error = $error, val = $val\n";
44 my (undef,$file,$line) = caller;
45 die "$error at $file line $line.\n";
49 *$AUTOLOAD = sub { $val };
57 if (($i eq 'clock_getres' && !&d_clock_getres) ||
58 ($i eq 'clock_gettime' && !&d_clock_gettime) ||
59 ($i eq 'clock_nanosleep' && !&d_clock_nanosleep) ||
60 ($i eq 'clock' && !&d_clock) ||
61 ($i eq 'nanosleep' && !&d_nanosleep) ||
62 ($i eq 'usleep' && !&d_usleep) ||
63 ($i eq 'ualarm' && !&d_ualarm)) {
65 Carp::croak("Time::HiRes::$i(): unimplemented in this platform");
68 Time::HiRes->export_to_level(1, $this, @_);
71 bootstrap Time::HiRes;
73 # Preloaded methods go here.
76 # probably could have been done in C
78 $b = [gettimeofday()] unless defined($b);
79 (${$b}[0] - ${$a}[0]) + ((${$b}[1] - ${$a}[1]) / 1_000_000);
82 # Autoload methods go after =cut, and are processed by the autosplit program.
89 Time::HiRes - High resolution alarm, sleep, gettimeofday, interval timers
93 use Time::HiRes qw( usleep ualarm gettimeofday tv_interval nanosleep
94 clock_gettime clock_getres clock_nanosleep clock
97 usleep ($microseconds);
98 nanosleep ($nanoseconds);
100 ualarm ($microseconds);
101 ualarm ($microseconds, $interval_microseconds);
103 $t0 = [gettimeofday];
104 ($seconds, $microseconds) = gettimeofday;
106 $elapsed = tv_interval ( $t0, [$seconds, $microseconds]);
107 $elapsed = tv_interval ( $t0, [gettimeofday]);
108 $elapsed = tv_interval ( $t0 );
110 use Time::HiRes qw ( time alarm sleep );
112 $now_fractions = time;
113 sleep ($floating_seconds);
114 alarm ($floating_seconds);
115 alarm ($floating_seconds, $floating_interval);
117 use Time::HiRes qw( setitimer getitimer );
119 setitimer ($which, $floating_seconds, $floating_interval );
122 use Time::HiRes qw( clock_gettime clock_getres clock_nanosleep
123 ITIMER_REAL ITIMER_VIRTUAL ITIMER_PROF ITIMER_REALPROF );
125 $realtime = clock_gettime(CLOCK_REALTIME);
126 $resolution = clock_getres(CLOCK_REALTIME);
128 clock_nanosleep(CLOCK_REALTIME, 1.5e9);
129 clock_nanosleep(CLOCK_REALTIME, time()*1e9 + 10e9, TIMER_ABSTIME);
131 my $ticktock = clock();
133 use Time::HiRes qw( stat lstat );
135 my @stat = stat("file");
137 my @stat = lstat("file");
141 The C<Time::HiRes> module implements a Perl interface to the
142 C<usleep>, C<nanosleep>, C<ualarm>, C<gettimeofday>, and
143 C<setitimer>/C<getitimer> system calls, in other words, high
144 resolution time and timers. See the L</EXAMPLES> section below and the
145 test scripts for usage; see your system documentation for the
146 description of the underlying C<nanosleep> or C<usleep>, C<ualarm>,
147 C<gettimeofday>, and C<setitimer>/C<getitimer> calls.
149 If your system lacks C<gettimeofday()> or an emulation of it you don't
150 get C<gettimeofday()> or the one-argument form of C<tv_interval()>.
151 If your system lacks all of C<nanosleep()>, C<usleep()>,
152 C<select()>, and C<poll>, you don't get C<Time::HiRes::usleep()>,
153 C<Time::HiRes::nanosleep()>, or C<Time::HiRes::sleep()>.
154 If your system lacks both C<ualarm()> and C<setitimer()> you don't get
155 C<Time::HiRes::ualarm()> or C<Time::HiRes::alarm()>.
157 If you try to import an unimplemented function in the C<use> statement
158 it will fail at compile time.
160 If your subsecond sleeping is implemented with C<nanosleep()> instead
161 of C<usleep()>, you can mix subsecond sleeping with signals since
162 C<nanosleep()> does not use signals. This, however, is not portable,
163 and you should first check for the truth value of
164 C<&Time::HiRes::d_nanosleep> to see whether you have nanosleep, and
165 then carefully read your C<nanosleep()> C API documentation for any
168 If you are using C<nanosleep> for something else than mixing sleeping
169 with signals, give some thought to whether Perl is the tool you should
170 be using for work requiring nanosecond accuracies.
172 Remember that unless you are working on a I<hard realtime> system,
173 any clocks and timers will be imprecise, especially so if you are working
174 in a pre-emptive multiuser system. Understand the difference between
175 I<wallclock time> and process time (in UNIX-like systems the sum of
176 I<user> and I<system> times). Any attempt to sleep for X seconds will
177 most probably end up sleeping B<more> than that, but don't be surprised
178 if you end up sleeping slightly B<less>.
180 The following functions can be imported from this module.
181 No functions are exported by default.
185 =item gettimeofday ()
187 In array context returns a two-element array with the seconds and
188 microseconds since the epoch. In scalar context returns floating
189 seconds like C<Time::HiRes::time()> (see below).
191 =item usleep ( $useconds )
193 Sleeps for the number of microseconds (millionths of a second)
194 specified. Returns the number of microseconds actually slept.
195 Can sleep for more than one second, unlike the C<usleep> system call.
196 Can also sleep for zero seconds, which often works like a I<thread yield>.
197 See also C<Time::HiRes::usleep()>, C<Time::HiRes::sleep()>, and
198 C<Time::HiRes::clock_nanosleep()>.
200 Do not expect usleep() to be exact down to one microsecond.
202 =item nanosleep ( $nanoseconds )
204 Sleeps for the number of nanoseconds (1e9ths of a second) specified.
205 Returns the number of nanoseconds actually slept (accurate only to
206 microseconds, the nearest thousand of them). Can sleep for more than
207 one second. Can also sleep for zero seconds, which often works like
208 a I<thread yield>. See also C<Time::HiRes::sleep()>,
209 C<Time::HiRes::usleep()>, and C<Time::HiRes::clock_nanosleep()>.
211 Do not expect nanosleep() to be exact down to one nanosecond.
212 Getting even accuracy of one thousand nanoseconds is good.
214 =item ualarm ( $useconds [, $interval_useconds ] )
216 Issues a C<ualarm> call; the C<$interval_useconds> is optional and
217 will be zero if unspecified, resulting in C<alarm>-like behaviour.
219 Returns the remaining time in the alarm in microseconds, or C<undef>
220 if an error occurred.
222 ualarm(0) will cancel an outstanding ualarm().
224 Note that the interaction between alarms and sleeps is unspecified.
228 tv_interval ( $ref_to_gettimeofday [, $ref_to_later_gettimeofday] )
230 Returns the floating seconds between the two times, which should have
231 been returned by C<gettimeofday()>. If the second argument is omitted,
232 then the current time is used.
236 Returns a floating seconds since the epoch. This function can be
237 imported, resulting in a nice drop-in replacement for the C<time>
238 provided with core Perl; see the L</EXAMPLES> below.
240 B<NOTE 1>: This higher resolution timer can return values either less
241 or more than the core C<time()>, depending on whether your platform
242 rounds the higher resolution timer values up, down, or to the nearest second
243 to get the core C<time()>, but naturally the difference should be never
244 more than half a second. See also L</clock_getres>, if available
247 B<NOTE 2>: Since Sunday, September 9th, 2001 at 01:46:40 AM GMT, when
248 the C<time()> seconds since epoch rolled over to 1_000_000_000, the
249 default floating point format of Perl and the seconds since epoch have
250 conspired to produce an apparent bug: if you print the value of
251 C<Time::HiRes::time()> you seem to be getting only five decimals, not
252 six as promised (microseconds). Not to worry, the microseconds are
253 there (assuming your platform supports such granularity in the first
254 place). What is going on is that the default floating point format of
255 Perl only outputs 15 digits. In this case that means ten digits
256 before the decimal separator and five after. To see the microseconds
257 you can use either C<printf>/C<sprintf> with C<"%.6f">, or the
258 C<gettimeofday()> function in list context, which will give you the
259 seconds and microseconds as two separate values.
261 =item sleep ( $floating_seconds )
263 Sleeps for the specified amount of seconds. Returns the number of
264 seconds actually slept (a floating point value). This function can
265 be imported, resulting in a nice drop-in replacement for the C<sleep>
266 provided with perl, see the L</EXAMPLES> below.
268 Note that the interaction between alarms and sleeps is unspecified.
270 =item alarm ( $floating_seconds [, $interval_floating_seconds ] )
272 The C<SIGALRM> signal is sent after the specified number of seconds.
273 Implemented using C<setitimer()> if available, C<ualarm()> if not.
274 The C<$interval_floating_seconds> argument is optional and will be
275 zero if unspecified, resulting in C<alarm()>-like behaviour. This
276 function can be imported, resulting in a nice drop-in replacement for
277 the C<alarm> provided with perl, see the L</EXAMPLES> below.
279 Returns the remaining time in the alarm in seconds, or C<undef>
280 if an error occurred.
282 B<NOTE 1>: With some combinations of operating systems and Perl
283 releases C<SIGALRM> restarts C<select()>, instead of interrupting it.
284 This means that an C<alarm()> followed by a C<select()> may together
285 take the sum of the times specified for the C<alarm()> and the
286 C<select()>, not just the time of the C<alarm()>.
288 Note that the interaction between alarms and sleeps is unspecified.
290 =item setitimer ( $which, $floating_seconds [, $interval_floating_seconds ] )
292 Start up an interval timer: after a certain time, a signal ($which) arrives,
293 and more signals may keep arriving at certain intervals. To disable
294 an "itimer", use C<$floating_seconds> of zero. If the
295 C<$interval_floating_seconds> is set to zero (or unspecified), the
296 timer is disabled B<after> the next delivered signal.
298 Use of interval timers may interfere with C<alarm()>, C<sleep()>,
299 and C<usleep()>. In standard-speak the "interaction is unspecified",
300 which means that I<anything> may happen: it may work, it may not.
302 In scalar context, the remaining time in the timer is returned.
304 In list context, both the remaining time and the interval are returned.
306 There are usually three or four interval timers (signals) available: the
307 C<$which> can be C<ITIMER_REAL>, C<ITIMER_VIRTUAL>, C<ITIMER_PROF>, or
308 C<ITIMER_REALPROF>. Note that which ones are available depends: true
309 UNIX platforms usually have the first three, but only Solaris seems to
310 have C<ITIMER_REALPROF> (which is used to profile multithreaded programs).
311 Win32 unfortunately does not have interval timers.
313 C<ITIMER_REAL> results in C<alarm()>-like behaviour. Time is counted in
314 I<real time>; that is, wallclock time. C<SIGALRM> is delivered when
317 C<ITIMER_VIRTUAL> counts time in (process) I<virtual time>; that is,
318 only when the process is running. In multiprocessor/user/CPU systems
319 this may be more or less than real or wallclock time. (This time is
320 also known as the I<user time>.) C<SIGVTALRM> is delivered when the
323 C<ITIMER_PROF> counts time when either the process virtual time or when
324 the operating system is running on behalf of the process (such as I/O).
325 (This time is also known as the I<system time>.) (The sum of user
326 time and system time is known as the I<CPU time>.) C<SIGPROF> is
327 delivered when the timer expires. C<SIGPROF> can interrupt system calls.
329 The semantics of interval timers for multithreaded programs are
330 system-specific, and some systems may support additional interval
331 timers. For example, it is unspecified which thread gets the signals.
332 See your C<setitimer()> documentation.
334 =item getitimer ( $which )
336 Return the remaining time in the interval timer specified by C<$which>.
338 In scalar context, the remaining time is returned.
340 In list context, both the remaining time and the interval are returned.
341 The interval is always what you put in using C<setitimer()>.
343 =item clock_gettime ( $which )
345 Return as seconds the current value of the POSIX high resolution timer
346 specified by C<$which>. All implementations that support POSIX high
347 resolution timers are supposed to support at least the C<$which> value
348 of C<CLOCK_REALTIME>, which is supposed to return results close to the
349 results of C<gettimeofday>, or the number of seconds since 00:00:00:00
350 January 1, 1970 Greenwich Mean Time (GMT). Do not assume that
351 CLOCK_REALTIME is zero, it might be one, or something else.
352 Another potentially useful (but not available everywhere) value is
353 C<CLOCK_MONOTONIC>, which guarantees a monotonically increasing time
354 value (unlike time() or gettimeofday(), which can be adjusted).
355 See your system documentation for other possibly supported values.
357 =item clock_getres ( $which )
359 Return as seconds the resolution of the POSIX high resolution timer
360 specified by C<$which>. All implementations that support POSIX high
361 resolution timers are supposed to support at least the C<$which> value
362 of C<CLOCK_REALTIME>, see L</clock_gettime>.
364 =item clock_nanosleep ( $which, $nanoseconds, $flags = 0)
366 Sleeps for the number of nanoseconds (1e9ths of a second) specified.
367 Returns the number of nanoseconds actually slept. The $which is the
368 "clock id", as with clock_gettime() and clock_getres(). The flags
369 default to zero but C<TIMER_ABSTIME> can specified (must be exported
370 explicitly) which means that C<$nanoseconds> is not a time interval
371 (as is the default) but instead an absolute time. Can sleep for more
372 than one second. Can also sleep for zero seconds, which often works
373 like a I<thread yield>. See also C<Time::HiRes::sleep()>,
374 C<Time::HiRes::usleep()>, and C<Time::HiRes::nanosleep()>.
376 Do not expect clock_nanosleep() to be exact down to one nanosecond.
377 Getting even accuracy of one thousand nanoseconds is good.
381 Return as seconds the I<process time> (user + system time) spent by
382 the process since the first call to clock() (the definition is B<not>
383 "since the start of the process", though if you are lucky these times
384 may be quite close to each other, depending on the system). What this
385 means is that you probably need to store the result of your first call
386 to clock(), and subtract that value from the following results of clock().
388 The time returned also includes the process times of the terminated
389 child processes for which wait() has been executed. This value is
390 somewhat like the second value returned by the times() of core Perl,
391 but not necessarily identical. Note that due to backward
392 compatibility limitations the returned value may wrap around at about
393 2147 seconds or at about 36 minutes.
407 As L<perlfunc/stat> or L<perlfunc/lstat>
408 but with the access/modify/change file timestamps
409 in subsecond resolution, if the operating system and the filesystem
410 both support such timestamps. To override the standard stat():
412 use Time::HiRes qw(stat);
414 Test for the value of &Time::HiRes::d_hires_stat to find out whether
415 the operating system supports subsecond file timestamps: a value
416 larger than zero means yes. There are unfortunately no easy
417 ways to find out whether the filesystem supports such timestamps.
418 UNIX filesystems often do; NTFS does; FAT doesn't (FAT timestamp
419 granularity is B<two> seconds).
421 A zero return value of &Time::HiRes::d_hires_stat means that
422 Time::HiRes::stat is a no-op passthrough for CORE::stat()
423 (and likewise for lstat),
424 and therefore the timestamps will stay integers. The same
425 thing will happen if the filesystem does not do subsecond timestamps,
426 even if the &Time::HiRes::d_hires_stat is non-zero.
428 In any case do not expect nanosecond resolution, or even a microsecond
429 resolution. Also note that the modify/access timestamps might have
430 different resolutions, and that they need not be synchronized, e.g.
431 if the operations are
438 the access time stamp from t2 need not be greater-than the modify
439 time stamp from t1: it may be equal or I<less>.
445 use Time::HiRes qw(usleep ualarm gettimeofday tv_interval);
447 $microseconds = 750_000;
448 usleep($microseconds);
450 # signal alarm in 2.5s & every .1s thereafter
451 ualarm(2_500_000, 100_000);
455 # get seconds and microseconds since the epoch
456 ($s, $usec) = gettimeofday();
458 # measure elapsed time
459 # (could also do by subtracting 2 gettimeofday return values)
460 $t0 = [gettimeofday];
461 # do bunch of stuff here
462 $t1 = [gettimeofday];
464 $t0_t1 = tv_interval $t0, $t1;
466 $elapsed = tv_interval ($t0, [gettimeofday]);
467 $elapsed = tv_interval ($t0); # equivalent code
470 # replacements for time, alarm and sleep that know about
474 $now_fractions = Time::HiRes::time;
475 Time::HiRes::sleep (2.5);
476 Time::HiRes::alarm (10.6666666);
478 use Time::HiRes qw ( time alarm sleep );
479 $now_fractions = time;
483 # Arm an interval timer to go off first at 10 seconds and
484 # after that every 2.5 seconds, in process virtual time
486 use Time::HiRes qw ( setitimer ITIMER_VIRTUAL time );
488 $SIG{VTALRM} = sub { print time, "\n" };
489 setitimer(ITIMER_VIRTUAL, 10, 2.5);
491 use Time::HiRes qw( clock_gettime clock_getres CLOCK_REALTIME );
492 # Read the POSIX high resolution timer.
493 my $high = clock_gettime(CLOCK_REALTIME);
494 # But how accurate we can be, really?
495 my $reso = clock_getres(CLOCK_REALTIME);
497 use Time::HiRes qw( clock_nanosleep TIMER_ABSTIME );
498 clock_nanosleep(CLOCK_REALTIME, 1e6);
499 clock_nanosleep(CLOCK_REALTIME, 2e9, TIMER_ABSTIME);
501 use Time::HiRes qw( clock );
502 my $clock0 = clock();
504 my $clock1 = clock();
505 my $clockd = $clock1 - $clock0;
507 use Time::HiRes qw( stat );
508 my ($atime, $mtime, $ctime) = (stat("istics"))[8, 9, 10];
512 In addition to the perl API described above, a C API is available for
513 extension writers. The following C functions are available in the
517 --------------- ----------------------
518 Time::NVtime NV (*)()
519 Time::U2time void (*)(pTHX_ UV ret[2])
521 Both functions return equivalent information (like C<gettimeofday>)
522 but with different representations. The names C<NVtime> and C<U2time>
523 were selected mainly because they are operating system independent.
524 (C<gettimeofday> is Unix-centric, though some platforms like Win32 and
525 VMS have emulations for it.)
527 Here is an example of using C<NVtime> from C:
529 NV (*myNVtime)(); /* Returns -1 on failure. */
530 SV **svp = hv_fetch(PL_modglobal, "Time::NVtime", 12, 0);
531 if (!svp) croak("Time::HiRes is required");
532 if (!SvIOK(*svp)) croak("Time::NVtime isn't a function pointer");
533 myNVtime = INT2PTR(NV(*)(), SvIV(*svp));
534 printf("The current time is: %" NVff "\n", (*myNVtime)());
538 =head2 useconds or interval more than ...
540 In ualarm() you tried to use number of microseconds or interval (also
541 in microseconds) more than 1_000_000 and setitimer() is not available
542 in your system to emulate that case.
544 =head2 negative time not invented yet
546 You tried to use a negative time argument.
548 =head2 internal error: useconds < 0 (unsigned ... signed ...)
550 Something went horribly wrong-- the number of microseconds that cannot
551 become negative just became negative. Maybe your compiler is broken?
553 =head2 useconds or uinterval equal to or more than 1000000
555 In some platforms it is not possible to get an alarm with subsecond
556 resolution and later than one second.
558 =head2 unimplemented in this platform
560 Some calls simply aren't available, real or emulated, on every platform.
564 Notice that the core C<time()> maybe rounding rather than truncating.
565 What this means is that the core C<time()> may be reporting the time
566 as one second later than C<gettimeofday()> and C<Time::HiRes::time()>.
568 Adjusting the system clock (either manually or by services like ntp)
569 may cause problems, especially for long running programs that assume
570 a monotonously increasing time (note that all platforms do not adjust
571 time as gracefully as UNIX ntp does). For example in Win32 (and derived
572 platforms like Cygwin and MinGW) the Time::HiRes::time() may temporarily
573 drift off from the system clock (and the original time()) by up to 0.5
574 seconds. Time::HiRes will notice this eventually and recalibrate.
575 Note that since Time::HiRes 1.77 the clock_gettime(CLOCK_MONOTONIC)
576 might help in this (in case your system supports CLOCK_MONOTONIC).
578 Some systems have APIs but not implementations: for example QNX and Haiku
579 have the interval timer APIs but not the functionality.
581 In OS X clock_getres(), clock_gettime() and clock_nanosleep() are
582 emulated using the Mach timers; as a side effect of being emulated
583 the CLOCK_REALTIME and CLOCK_MONOTONIC are the same timer.
587 Perl modules L<BSD::Resource>, L<Time::TAI64>.
589 Your system documentation for C<clock>, C<clock_gettime>,
590 C<clock_getres>, C<clock_nanosleep>, C<clock_settime>, C<getitimer>,
591 C<gettimeofday>, C<setitimer>, C<sleep>, C<stat>, C<ualarm>.
595 D. Wegscheid <wegscd@whirlpool.com>
596 R. Schertler <roderick@argon.org>
597 J. Hietaniemi <jhi@iki.fi>
598 G. Aas <gisle@aas.no>
600 =head1 COPYRIGHT AND LICENSE
602 Copyright (c) 1996-2002 Douglas E. Wegscheid. All rights reserved.
604 Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007, 2008 Jarkko Hietaniemi.
607 Copyright (C) 2011, 2012, 2013 Andrew Main (Zefram) <zefram@fysh.org>
609 This program is free software; you can redistribute it and/or modify
610 it under the same terms as Perl itself.