4 use vars qw($VERSION $XS_VERSION @ISA @EXPORT @EXPORT_OK $AUTOLOAD);
9 @ISA = qw(Exporter DynaLoader);
12 @EXPORT_OK = qw (usleep sleep ualarm alarm gettimeofday time tv_interval
13 getitimer setitimer nanosleep clock_gettime clock_getres
15 CLOCK_HIGHRES CLOCK_MONOTONIC CLOCK_PROCESS_CPUTIME_ID
16 CLOCK_REALTIME CLOCK_SOFTTIME CLOCK_THREAD_CPUTIME_ID
17 CLOCK_TIMEOFDAY CLOCKS_PER_SEC
18 ITIMER_REAL ITIMER_VIRTUAL ITIMER_PROF ITIMER_REALPROF
20 d_usleep d_ualarm d_gettimeofday d_getitimer d_setitimer
21 d_nanosleep d_clock_gettime d_clock_getres
22 d_clock d_clock_nanosleep
27 $XS_VERSION = $VERSION;
28 $VERSION = eval $VERSION;
32 ($constname = $AUTOLOAD) =~ s/.*:://;
33 # print "AUTOLOAD: constname = $constname ($AUTOLOAD)\n";
34 die "&Time::HiRes::constant not defined" if $constname eq 'constant';
35 my ($error, $val) = constant($constname);
36 # print "AUTOLOAD: error = $error, val = $val\n";
38 my (undef,$file,$line) = caller;
39 die "$error at $file line $line.\n";
43 *$AUTOLOAD = sub { $val };
51 if (($i eq 'clock_getres' && !&d_clock_getres) ||
52 ($i eq 'clock_gettime' && !&d_clock_gettime) ||
53 ($i eq 'clock_nanosleep' && !&d_clock_nanosleep) ||
54 ($i eq 'clock' && !&d_clock) ||
55 ($i eq 'nanosleep' && !&d_nanosleep) ||
56 ($i eq 'usleep' && !&d_usleep) ||
57 ($i eq 'ualarm' && !&d_ualarm)) {
59 Carp::croak("Time::HiRes::$i(): unimplemented in this platform");
62 Time::HiRes->export_to_level(1, $this, @_);
65 bootstrap Time::HiRes;
67 # Preloaded methods go here.
70 # probably could have been done in C
72 $b = [gettimeofday()] unless defined($b);
73 (${$b}[0] - ${$a}[0]) + ((${$b}[1] - ${$a}[1]) / 1_000_000);
76 # Autoload methods go after =cut, and are processed by the autosplit program.
83 Time::HiRes - High resolution alarm, sleep, gettimeofday, interval timers
87 use Time::HiRes qw( usleep ualarm gettimeofday tv_interval nanosleep
88 clock_gettime clock_getres clock_nanosleep clock
91 usleep ($microseconds);
92 nanosleep ($nanoseconds);
94 ualarm ($microseconds);
95 ualarm ($microseconds, $interval_microseconds);
98 ($seconds, $microseconds) = gettimeofday;
100 $elapsed = tv_interval ( $t0, [$seconds, $microseconds]);
101 $elapsed = tv_interval ( $t0, [gettimeofday]);
102 $elapsed = tv_interval ( $t0 );
104 use Time::HiRes qw ( time alarm sleep );
106 $now_fractions = time;
107 sleep ($floating_seconds);
108 alarm ($floating_seconds);
109 alarm ($floating_seconds, $floating_interval);
111 use Time::HiRes qw( setitimer getitimer );
113 setitimer ($which, $floating_seconds, $floating_interval );
116 use Time::HiRes qw( clock_gettime clock_getres clock_nanosleep
117 ITIMER_REAL ITIMER_VIRTUAL ITIMER_PROF ITIMER_REALPROF );
119 $realtime = clock_gettime(CLOCK_REALTIME);
120 $resolution = clock_getres(CLOCK_REALTIME);
122 clock_nanosleep(CLOCK_REALTIME, 1.5e9);
123 clock_nanosleep(CLOCK_REALTIME, time()*1e9 + 10e9, TIMER_ABSTIME);
125 my $ticktock = clock();
127 use Time::HiRes qw( stat );
129 my @stat = stat("file");
134 The C<Time::HiRes> module implements a Perl interface to the
135 C<usleep>, C<nanosleep>, C<ualarm>, C<gettimeofday>, and
136 C<setitimer>/C<getitimer> system calls, in other words, high
137 resolution time and timers. See the L</EXAMPLES> section below and the
138 test scripts for usage; see your system documentation for the
139 description of the underlying C<nanosleep> or C<usleep>, C<ualarm>,
140 C<gettimeofday>, and C<setitimer>/C<getitimer> calls.
142 If your system lacks C<gettimeofday()> or an emulation of it you don't
143 get C<gettimeofday()> or the one-argument form of C<tv_interval()>.
144 If your system lacks all of C<nanosleep()>, C<usleep()>,
145 C<select()>, and C<poll>, you don't get C<Time::HiRes::usleep()>,
146 C<Time::HiRes::nanosleep()>, or C<Time::HiRes::sleep()>.
147 If your system lacks both C<ualarm()> and C<setitimer()> you don't get
148 C<Time::HiRes::ualarm()> or C<Time::HiRes::alarm()>.
150 If you try to import an unimplemented function in the C<use> statement
151 it will fail at compile time.
153 If your subsecond sleeping is implemented with C<nanosleep()> instead
154 of C<usleep()>, you can mix subsecond sleeping with signals since
155 C<nanosleep()> does not use signals. This, however, is not portable,
156 and you should first check for the truth value of
157 C<&Time::HiRes::d_nanosleep> to see whether you have nanosleep, and
158 then carefully read your C<nanosleep()> C API documentation for any
161 If you are using C<nanosleep> for something else than mixing sleeping
162 with signals, give some thought to whether Perl is the tool you should
163 be using for work requiring nanosecond accuracies.
165 Remember that unless you are working on a I<hard realtime> system,
166 any clocks and timers will be imprecise, especially so if you are working
167 in a pre-emptive multiuser system. Understand the difference between
168 I<wallclock time> and process time (in UNIX-like systems the sum of
169 I<user> and I<system> times). Any attempt to sleep for X seconds will
170 most probably end up sleeping B<more> than that, but don't be surpised
171 if you end up sleeping slightly B<less>.
173 The following functions can be imported from this module.
174 No functions are exported by default.
178 =item gettimeofday ()
180 In array context returns a two-element array with the seconds and
181 microseconds since the epoch. In scalar context returns floating
182 seconds like C<Time::HiRes::time()> (see below).
184 =item usleep ( $useconds )
186 Sleeps for the number of microseconds (millionths of a second)
187 specified. Returns the number of microseconds actually slept.
188 Can sleep for more than one second, unlike the C<usleep> system call.
189 Can also sleep for zero seconds, which often works like a I<thread yield>.
190 See also C<Time::HiRes::usleep()>, C<Time::HiRes::sleep()>, and
191 C<Time::HiRes::clock_nanosleep()>.
193 Do not expect usleep() to be exact down to one microsecond.
195 =item nanosleep ( $nanoseconds )
197 Sleeps for the number of nanoseconds (1e9ths of a second) specified.
198 Returns the number of nanoseconds actually slept (accurate only to
199 microseconds, the nearest thousand of them). Can sleep for more than
200 one second. Can also sleep for zero seconds, which often works like
201 a I<thread yield>. See also C<Time::HiRes::sleep()>,
202 C<Time::HiRes::usleep()>, and C<Time::HiRes::clock_nanosleep()>.
204 Do not expect nanosleep() to be exact down to one nanosecond.
205 Getting even accuracy of one thousand nanoseconds is good.
207 =item ualarm ( $useconds [, $interval_useconds ] )
209 Issues a C<ualarm> call; the C<$interval_useconds> is optional and
210 will be zero if unspecified, resulting in C<alarm>-like behaviour.
212 ualarm(0) will cancel an outstanding ualarm().
214 Note that the interaction between alarms and sleeps is unspecified.
218 tv_interval ( $ref_to_gettimeofday [, $ref_to_later_gettimeofday] )
220 Returns the floating seconds between the two times, which should have
221 been returned by C<gettimeofday()>. If the second argument is omitted,
222 then the current time is used.
226 Returns a floating seconds since the epoch. This function can be
227 imported, resulting in a nice drop-in replacement for the C<time>
228 provided with core Perl; see the L</EXAMPLES> below.
230 B<NOTE 1>: This higher resolution timer can return values either less
231 or more than the core C<time()>, depending on whether your platform
232 rounds the higher resolution timer values up, down, or to the nearest second
233 to get the core C<time()>, but naturally the difference should be never
234 more than half a second. See also L</clock_getres>, if available
237 B<NOTE 2>: Since Sunday, September 9th, 2001 at 01:46:40 AM GMT, when
238 the C<time()> seconds since epoch rolled over to 1_000_000_000, the
239 default floating point format of Perl and the seconds since epoch have
240 conspired to produce an apparent bug: if you print the value of
241 C<Time::HiRes::time()> you seem to be getting only five decimals, not
242 six as promised (microseconds). Not to worry, the microseconds are
243 there (assuming your platform supports such granularity in the first
244 place). What is going on is that the default floating point format of
245 Perl only outputs 15 digits. In this case that means ten digits
246 before the decimal separator and five after. To see the microseconds
247 you can use either C<printf>/C<sprintf> with C<"%.6f">, or the
248 C<gettimeofday()> function in list context, which will give you the
249 seconds and microseconds as two separate values.
251 =item sleep ( $floating_seconds )
253 Sleeps for the specified amount of seconds. Returns the number of
254 seconds actually slept (a floating point value). This function can
255 be imported, resulting in a nice drop-in replacement for the C<sleep>
256 provided with perl, see the L</EXAMPLES> below.
258 Note that the interaction between alarms and sleeps is unspecified.
260 =item alarm ( $floating_seconds [, $interval_floating_seconds ] )
262 The C<SIGALRM> signal is sent after the specified number of seconds.
263 Implemented using C<ualarm()>. The C<$interval_floating_seconds> argument
264 is optional and will be zero if unspecified, resulting in C<alarm()>-like
265 behaviour. This function can be imported, resulting in a nice drop-in
266 replacement for the C<alarm> provided with perl, see the L</EXAMPLES> below.
268 B<NOTE 1>: With some combinations of operating systems and Perl
269 releases C<SIGALRM> restarts C<select()>, instead of interrupting it.
270 This means that an C<alarm()> followed by a C<select()> may together
271 take the sum of the times specified for the the C<alarm()> and the
272 C<select()>, not just the time of the C<alarm()>.
274 Note that the interaction between alarms and sleeps is unspecified.
276 =item setitimer ( $which, $floating_seconds [, $interval_floating_seconds ] )
278 Start up an interval timer: after a certain time, a signal ($which) arrives,
279 and more signals may keep arriving at certain intervals. To disable
280 an "itimer", use C<$floating_seconds> of zero. If the
281 C<$interval_floating_seconds> is set to zero (or unspecified), the
282 timer is disabled B<after> the next delivered signal.
284 Use of interval timers may interfere with C<alarm()>, C<sleep()>,
285 and C<usleep()>. In standard-speak the "interaction is unspecified",
286 which means that I<anything> may happen: it may work, it may not.
288 In scalar context, the remaining time in the timer is returned.
290 In list context, both the remaining time and the interval are returned.
292 There are usually three or four interval timers (signals) available: the
293 C<$which> can be C<ITIMER_REAL>, C<ITIMER_VIRTUAL>, C<ITIMER_PROF>, or
294 C<ITIMER_REALPROF>. Note that which ones are available depends: true
295 UNIX platforms usually have the first three, but (for example) Win32
296 and Cygwin have only C<ITIMER_REAL>, and only Solaris seems to have
297 C<ITIMER_REALPROF> (which is used to profile multithreaded programs).
299 C<ITIMER_REAL> results in C<alarm()>-like behaviour. Time is counted in
300 I<real time>; that is, wallclock time. C<SIGALRM> is delivered when
303 C<ITIMER_VIRTUAL> counts time in (process) I<virtual time>; that is,
304 only when the process is running. In multiprocessor/user/CPU systems
305 this may be more or less than real or wallclock time. (This time is
306 also known as the I<user time>.) C<SIGVTALRM> is delivered when the
309 C<ITIMER_PROF> counts time when either the process virtual time or when
310 the operating system is running on behalf of the process (such as I/O).
311 (This time is also known as the I<system time>.) (The sum of user
312 time and system time is known as the I<CPU time>.) C<SIGPROF> is
313 delivered when the timer expires. C<SIGPROF> can interrupt system calls.
315 The semantics of interval timers for multithreaded programs are
316 system-specific, and some systems may support additional interval
317 timers. For example, it is unspecified which thread gets the signals.
318 See your C<setitimer()> documentation.
320 =item getitimer ( $which )
322 Return the remaining time in the interval timer specified by C<$which>.
324 In scalar context, the remaining time is returned.
326 In list context, both the remaining time and the interval are returned.
327 The interval is always what you put in using C<setitimer()>.
329 =item clock_gettime ( $which )
331 Return as seconds the current value of the POSIX high resolution timer
332 specified by C<$which>. All implementations that support POSIX high
333 resolution timers are supposed to support at least the C<$which> value
334 of C<CLOCK_REALTIME>, which is supposed to return results close to the
335 results of C<gettimeofday>, or the number of seconds since 00:00:00:00
336 January 1, 1970 Greenwich Mean Time (GMT). Do not assume that
337 CLOCK_REALTIME is zero, it might be one, or something else.
338 Another potentially useful (but not available everywhere) value is
339 C<CLOCK_MONOTONIC>, which guarantees a monotonically increasing time
340 value (unlike time(), which can be adjusted). See your system
341 documentation for other possibly supported values.
343 =item clock_getres ( $which )
345 Return as seconds the resolution 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>, see L</clock_gettime>.
350 =item clock_nanosleep ( $which, $nanoseconds, $flags = 0)
352 Sleeps for the number of nanoseconds (1e9ths of a second) specified.
353 Returns the number of nanoseconds actually slept. The $which is the
354 "clock id", as with clock_gettime() and clock_getres(). The flags
355 default to zero but C<TIMER_ABSTIME> can specified (must be exported
356 explicitly) which means that C<$nanoseconds> is not a time interval
357 (as is the default) but instead an absolute time. Can sleep for more
358 than one second. Can also sleep for zero seconds, which often works
359 like a I<thread yield>. See also C<Time::HiRes::sleep()>,
360 C<Time::HiRes::usleep()>, and C<Time::HiRes::nanosleep()>.
362 Do not expect clock_nanosleep() to be exact down to one nanosecond.
363 Getting even accuracy of one thousand nanoseconds is good.
367 Return as seconds the I<process time> (user + system time) spent by
368 the process since the first call to clock() (the definition is B<not>
369 "since the start of the process", though if you are lucky these times
370 may be quite close to each other, depending on the system). What this
371 means is that you probably need to store the result of your first call
372 to clock(), and subtract that value from the following results of clock().
374 The time returned also includes the process times of the terminated
375 child processes for which wait() has been executed. This value is
376 somewhat like the second value returned by the times() of core Perl,
377 but not necessarily identical. Note that due to backward
378 compatibility limitations the returned value may wrap around at about
379 2147 seconds or at about 36 minutes.
387 As L<perlfunc/stat> but with the access/modify/change file timestamps
388 in subsecond resolution, if the operating system and the filesystem
389 both support such timestamps. To override the standard stat():
391 use Time::HiRes qw(stat);
393 Test for the value of &Time::HiRes::d_hires_stat to find out whether
394 the operating system supports subsecond file timestamps: a value
395 larger than zero means yes. There are unfortunately no easy
396 ways to find out whether the filesystem supports such timestamps.
397 UNIX filesystems often do; NTFS does; FAT doesn't (FAT timestamp
398 granularity is B<two> seconds).
400 A zero return value of &Time::HiRes::d_hires_stat means that
401 Time::HiRes::stat is a no-op passthrough for CORE::stat(),
402 and therefore the timestamps will stay integers. The same
403 thing will happen if the filesystem does not do subsecond timestamps,
404 even if the &Time::HiRes::d_hires_stat is non-zero.
406 In any case do not expect nanosecond resolution, or even a microsecond
407 resolution. Also note that the modify/access timestamps might have
408 different resolutions, and that they need not be synchronized, e.g.
409 if the operations are
416 the access time stamp from t2 need not be greater-than the modify
417 time stamp from t1: it may be equal or I<less>.
423 use Time::HiRes qw(usleep ualarm gettimeofday tv_interval);
425 $microseconds = 750_000;
426 usleep($microseconds);
428 # signal alarm in 2.5s & every .1s thereafter
429 ualarm(2_500_000, 100_000);
433 # get seconds and microseconds since the epoch
434 ($s, $usec) = gettimeofday();
436 # measure elapsed time
437 # (could also do by subtracting 2 gettimeofday return values)
438 $t0 = [gettimeofday];
439 # do bunch of stuff here
440 $t1 = [gettimeofday];
442 $t0_t1 = tv_interval $t0, $t1;
444 $elapsed = tv_interval ($t0, [gettimeofday]);
445 $elapsed = tv_interval ($t0); # equivalent code
448 # replacements for time, alarm and sleep that know about
452 $now_fractions = Time::HiRes::time;
453 Time::HiRes::sleep (2.5);
454 Time::HiRes::alarm (10.6666666);
456 use Time::HiRes qw ( time alarm sleep );
457 $now_fractions = time;
461 # Arm an interval timer to go off first at 10 seconds and
462 # after that every 2.5 seconds, in process virtual time
464 use Time::HiRes qw ( setitimer ITIMER_VIRTUAL time );
466 $SIG{VTALRM} = sub { print time, "\n" };
467 setitimer(ITIMER_VIRTUAL, 10, 2.5);
469 use Time::HiRes qw( clock_gettime clock_getres CLOCK_REALTIME );
470 # Read the POSIX high resolution timer.
471 my $high = clock_getres(CLOCK_REALTIME);
472 # But how accurate we can be, really?
473 my $reso = clock_getres(CLOCK_REALTIME);
475 use Time::HiRes qw( clock_nanosleep TIMER_ABSTIME );
476 clock_nanosleep(CLOCK_REALTIME, 1e6);
477 clock_nanosleep(CLOCK_REALTIME, 2e9, TIMER_ABSTIME);
479 use Time::HiRes qw( clock );
480 my $clock0 = clock();
482 my $clock1 = clock();
483 my $clockd = $clock1 - $clock0;
485 use Time::HiRes qw( stat );
486 my ($atime, $mtime, $ctime) = (stat("istics"))[8, 9, 10];
490 In addition to the perl API described above, a C API is available for
491 extension writers. The following C functions are available in the
495 --------------- ----------------------
496 Time::NVtime double (*)()
497 Time::U2time void (*)(pTHX_ UV ret[2])
499 Both functions return equivalent information (like C<gettimeofday>)
500 but with different representations. The names C<NVtime> and C<U2time>
501 were selected mainly because they are operating system independent.
502 (C<gettimeofday> is Unix-centric, though some platforms like Win32 and
503 VMS have emulations for it.)
505 Here is an example of using C<NVtime> from C:
507 double (*myNVtime)(); /* Returns -1 on failure. */
508 SV **svp = hv_fetch(PL_modglobal, "Time::NVtime", 12, 0);
509 if (!svp) croak("Time::HiRes is required");
510 if (!SvIOK(*svp)) croak("Time::NVtime isn't a function pointer");
511 myNVtime = INT2PTR(double(*)(), SvIV(*svp));
512 printf("The current time is: %f\n", (*myNVtime)());
516 =head2 useconds or interval more than ...
518 In ualarm() you tried to use number of microseconds or interval (also
519 in microseconds) more than 1_000_000 and setitimer() is not available
520 in your system to emulate that case.
522 =head2 negative time not invented yet
524 You tried to use a negative time argument.
526 =head2 internal error: useconds < 0 (unsigned ... signed ...)
528 Something went horribly wrong-- the number of microseconds that cannot
529 become negative just became negative. Maybe your compiler is broken?
533 Notice that the core C<time()> maybe rounding rather than truncating.
534 What this means is that the core C<time()> may be reporting the time
535 as one second later than C<gettimeofday()> and C<Time::HiRes::time()>.
537 Adjusting the system clock (either manually or by services like ntp)
538 may cause problems, especially for long running programs that assume
539 a monotonously increasing time (note that all platforms do not adjust
540 time as gracefully as UNIX ntp does). For example in Win32 (and derived
541 platforms like Cygwin and MinGW) the Time::HiRes::time() may temporarily
542 drift off from the system clock (and the original time()) by up to 0.5
543 seconds. Time::HiRes will notice this eventually and recalibrate.
544 Note that since Time::HiRes 1.77 the clock_gettime(CLOCK_MONOTONIC)
545 might help in this (in case your system supports CLOCK_MONOTONIC).
549 Perl modules L<BSD::Resource>, L<Time::TAI64>.
551 Your system documentation for C<clock>, C<clock_gettime>,
552 C<clock_getres>, C<clock_nanosleep>, C<clock_settime>, C<getitimer>,
553 C<gettimeofday>, C<setitimer>, C<sleep>, C<stat>, C<ualarm>.
557 D. Wegscheid <wegscd@whirlpool.com>
558 R. Schertler <roderick@argon.org>
559 J. Hietaniemi <jhi@iki.fi>
560 G. Aas <gisle@aas.no>
562 =head1 COPYRIGHT AND LICENSE
564 Copyright (c) 1996-2002 Douglas E. Wegscheid. All rights reserved.
566 Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007 Jarkko Hietaniemi. All rights reserved.
568 This program is free software; you can redistribute it and/or modify
569 it under the same terms as Perl itself.