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
14 CLOCK_HIGHRES CLOCK_MONOTONIC CLOCK_PROCESS_CPUTIME_ID
15 CLOCK_REALTIME CLOCK_THREAD_CPUTIME_ID CLOCK_TIMEOFDAY
16 ITIMER_REAL ITIMER_VIRTUAL ITIMER_PROF ITIMER_REALPROF
17 d_usleep d_ualarm d_gettimeofday d_getitimer d_setitimer
18 d_nanosleep d_clock_gettime d_clock_getres);
21 $XS_VERSION = $VERSION;
22 $VERSION = eval $VERSION;
26 ($constname = $AUTOLOAD) =~ s/.*:://;
27 # print "AUTOLOAD: constname = $constname ($AUTOLOAD)\n";
28 die "&Time::HiRes::constant not defined" if $constname eq 'constant';
29 my ($error, $val) = constant($constname);
30 # print "AUTOLOAD: error = $error, val = $val\n";
32 my (undef,$file,$line) = caller;
33 die "$error at $file line $line.\n";
37 *$AUTOLOAD = sub { $val };
45 if (($i eq 'clock_getres' && !&d_clock_getres) ||
46 ($i eq 'clock_gettime' && !&d_clock_gettime) ||
47 ($i eq 'nanosleep' && !&d_nanosleep) ||
48 ($i eq 'usleep' && !&d_usleep) ||
49 ($i eq 'ualarm' && !&d_ualarm)) {
51 Carp::croak("Time::HiRes::$i(): unimplemented in this platform");
54 Time::HiRes->export_to_level(1, $this, @_);
57 bootstrap Time::HiRes;
59 # Preloaded methods go here.
62 # probably could have been done in C
64 $b = [gettimeofday()] unless defined($b);
65 (${$b}[0] - ${$a}[0]) + ((${$b}[1] - ${$a}[1]) / 1_000_000);
68 # Autoload methods go after =cut, and are processed by the autosplit program.
75 Time::HiRes - High resolution alarm, sleep, gettimeofday, interval timers
79 use Time::HiRes qw( usleep ualarm gettimeofday tv_interval nanosleep
80 clock_gettime clock_getres );
82 usleep ($microseconds);
83 nanosleep ($nanoseconds);
85 ualarm ($microseconds);
86 ualarm ($microseconds, $interval_microseconds);
89 ($seconds, $microseconds) = gettimeofday;
91 $elapsed = tv_interval ( $t0, [$seconds, $microseconds]);
92 $elapsed = tv_interval ( $t0, [gettimeofday]);
93 $elapsed = tv_interval ( $t0 );
95 use Time::HiRes qw ( time alarm sleep );
97 $now_fractions = time;
98 sleep ($floating_seconds);
99 alarm ($floating_seconds);
100 alarm ($floating_seconds, $floating_interval);
102 use Time::HiRes qw( setitimer getitimer
103 ITIMER_REAL ITIMER_VIRTUAL ITIMER_PROF ITIMER_REALPROF );
105 setitimer ($which, $floating_seconds, $floating_interval );
108 $realtime = clock_gettime(CLOCK_REALTIME);
109 $resolution = clock_getres(CLOCK_REALTIME);
113 The C<Time::HiRes> module implements a Perl interface to the
114 C<usleep>, C<nanosleep>, C<ualarm>, C<gettimeofday>, and
115 C<setitimer>/C<getitimer> system calls, in other words, high
116 resolution time and timers. See the L</EXAMPLES> section below and the
117 test scripts for usage; see your system documentation for the
118 description of the underlying C<nanosleep> or C<usleep>, C<ualarm>,
119 C<gettimeofday>, and C<setitimer>/C<getitimer> calls.
121 If your system lacks C<gettimeofday()> or an emulation of it you don't
122 get C<gettimeofday()> or the one-argument form of C<tv_interval()>.
123 If your system lacks all of C<nanosleep()>, C<usleep()>,
124 C<select()>, and C<poll>, you don't get C<Time::HiRes::usleep()>,
125 C<Time::HiRes::nanosleep()>, or C<Time::HiRes::sleep()>.
126 If your system lacks both C<ualarm()> and C<setitimer()> you don't get
127 C<Time::HiRes::ualarm()> or C<Time::HiRes::alarm()>.
129 If you try to import an unimplemented function in the C<use> statement
130 it will fail at compile time.
132 If your subsecond sleeping is implemented with C<nanosleep()> instead
133 of C<usleep()>, you can mix subsecond sleeping with signals since
134 C<nanosleep()> does not use signals. This, however, is not portable,
135 and you should first check for the truth value of
136 C<&Time::HiRes::d_nanosleep> to see whether you have nanosleep, and
137 then carefully read your C<nanosleep()> C API documentation for any
140 If you are using C<nanosleep> for something else than mixing sleeping
141 with signals, give some thought to whether Perl is the tool you should
142 be using for work requiring nanosecond accuracies.
144 The following functions can be imported from this module.
145 No functions are exported by default.
149 =item gettimeofday ()
151 In array context returns a two-element array with the seconds and
152 microseconds since the epoch. In scalar context returns floating
153 seconds like C<Time::HiRes::time()> (see below).
155 =item usleep ( $useconds )
157 Sleeps for the number of microseconds (millionths of a second)
158 specified. Returns the number of microseconds actually slept. Can
159 sleep for more than one second, unlike the C<usleep> system call. See
160 also C<Time::HiRes::usleep()> and C<Time::HiRes::sleep()>.
162 Do not expect usleep() to be exact down to one microsecond.
164 =item nanosleep ( $nanoseconds )
166 Sleeps for the number of nanoseconds (1e9ths of a second) specified.
167 Returns the number of nanoseconds actually slept (accurate only to
168 microseconds, the nearest thousand of them). Can sleep for more than
169 one second. See also C<Time::HiRes::sleep()> and
170 C<Time::HiRes::usleep()>.
172 Do not expect nanosleep() to be exact down to one nanosecond.
173 Getting even accuracy of one thousand nanoseconds is good.
175 =item ualarm ( $useconds [, $interval_useconds ] )
177 Issues a C<ualarm> call; the C<$interval_useconds> is optional and
178 will be zero if unspecified, resulting in C<alarm>-like behaviour.
180 Note that the interaction between alarms and sleeps is unspecified.
184 tv_interval ( $ref_to_gettimeofday [, $ref_to_later_gettimeofday] )
186 Returns the floating seconds between the two times, which should have
187 been returned by C<gettimeofday()>. If the second argument is omitted,
188 then the current time is used.
192 Returns a floating seconds since the epoch. This function can be
193 imported, resulting in a nice drop-in replacement for the C<time>
194 provided with core Perl; see the L</EXAMPLES> below.
196 B<NOTE 1>: This higher resolution timer can return values either less
197 or more than the core C<time()>, depending on whether your platform
198 rounds the higher resolution timer values up, down, or to the nearest second
199 to get the core C<time()>, but naturally the difference should be never
200 more than half a second. See also L</clock_getres>, if available
203 B<NOTE 2>: Since Sunday, September 9th, 2001 at 01:46:40 AM GMT, when
204 the C<time()> seconds since epoch rolled over to 1_000_000_000, the
205 default floating point format of Perl and the seconds since epoch have
206 conspired to produce an apparent bug: if you print the value of
207 C<Time::HiRes::time()> you seem to be getting only five decimals, not
208 six as promised (microseconds). Not to worry, the microseconds are
209 there (assuming your platform supports such granularity in the first
210 place). What is going on is that the default floating point format of
211 Perl only outputs 15 digits. In this case that means ten digits
212 before the decimal separator and five after. To see the microseconds
213 you can use either C<printf>/C<sprintf> with C<"%.6f">, or the
214 C<gettimeofday()> function in list context, which will give you the
215 seconds and microseconds as two separate values.
217 =item sleep ( $floating_seconds )
219 Sleeps for the specified amount of seconds. Returns the number of
220 seconds actually slept (a floating point value). This function can
221 be imported, resulting in a nice drop-in replacement for the C<sleep>
222 provided with perl, see the L</EXAMPLES> below.
224 Note that the interaction between alarms and sleeps is unspecified.
226 =item alarm ( $floating_seconds [, $interval_floating_seconds ] )
228 The C<SIGALRM> signal is sent after the specified number of seconds.
229 Implemented using C<ualarm()>. The C<$interval_floating_seconds> argument
230 is optional and will be zero if unspecified, resulting in C<alarm()>-like
231 behaviour. This function can be imported, resulting in a nice drop-in
232 replacement for the C<alarm> provided with perl, see the L</EXAMPLES> below.
234 B<NOTE 1>: With some combinations of operating systems and Perl
235 releases C<SIGALRM> restarts C<select()>, instead of interrupting it.
236 This means that an C<alarm()> followed by a C<select()> may together
237 take the sum of the times specified for the the C<alarm()> and the
238 C<select()>, not just the time of the C<alarm()>.
240 Note that the interaction between alarms and sleeps is unspecified.
242 =item setitimer ( $which, $floating_seconds [, $interval_floating_seconds ] )
244 Start up an interval timer: after a certain time, a signal arrives,
245 and more signals may keep arriving at certain intervals. To disable
246 an "itimer", use C<$floating_seconds> of zero. If the
247 C<$interval_floating_seconds> is set to zero (or unspecified), the
248 timer is disabled B<after> the next delivered signal.
250 Use of interval timers may interfere with C<alarm()>, C<sleep()>,
251 and C<usleep()>. In standard-speak the "interaction is unspecified",
252 which means that I<anything> may happen: it may work, it may not.
254 In scalar context, the remaining time in the timer is returned.
256 In list context, both the remaining time and the interval are returned.
258 There are usually three or four interval timers available: the
259 C<$which> can be C<ITIMER_REAL>, C<ITIMER_VIRTUAL>, C<ITIMER_PROF>, or
260 C<ITIMER_REALPROF>. Note that which ones are available depends: true
261 UNIX platforms usually have the first three, but (for example) Win32
262 and Cygwin have only C<ITIMER_REAL>, and only Solaris seems to have
263 C<ITIMER_REALPROF> (which is used to profile multithreaded programs).
265 C<ITIMER_REAL> results in C<alarm()>-like behaviour. Time is counted in
266 I<real time>; that is, wallclock time. C<SIGALRM> is delivered when
269 C<ITIMER_VIRTUAL> counts time in (process) I<virtual time>; that is,
270 only when the process is running. In multiprocessor/user/CPU systems
271 this may be more or less than real or wallclock time. (This time is
272 also known as the I<user time>.) C<SIGVTALRM> is delivered when the
275 C<ITIMER_PROF> counts time when either the process virtual time or when
276 the operating system is running on behalf of the process (such as I/O).
277 (This time is also known as the I<system time>.) (The sum of user
278 time and system time is known as the I<CPU time>.) C<SIGPROF> is
279 delivered when the timer expires. C<SIGPROF> can interrupt system calls.
281 The semantics of interval timers for multithreaded programs are
282 system-specific, and some systems may support additional interval
283 timers. See your C<setitimer()> documentation.
285 =item getitimer ( $which )
287 Return the remaining time in the interval timer specified by C<$which>.
289 In scalar context, the remaining time is returned.
291 In list context, both the remaining time and the interval are returned.
292 The interval is always what you put in using C<setitimer()>.
294 =item clock_gettime ( $which )
296 Return as seconds the current value of the POSIX high resolution timer
297 specified by C<$which>. All implementations that support POSIX high
298 resolution timers are supposed to support at least the C<$which> value
299 of C<CLOCK_REALTIME>, which is supposed to return results close to the
300 results of C<gettimeofday>, or the number of seconds since 00:00:00:00
301 January 1, 1970 Greenwich Mean Time (GMT). Do not assume that
302 CLOCK_REALTIME is zero, it might be one, or something else.
303 Another potentially useful (but not available everywhere) value is
304 C<CLOCK_MONOTONIC>, which guarantees a monotonically increasing time
305 value (unlike time(), which can be adjusted). See your system
306 documentation for other possibly supported values.
308 =item clock_getres ( $which )
310 Return as seconds the resolution of the POSIX high resolution timer
311 specified by C<$which>. All implementations that support POSIX high
312 resolution timers are supposed to support at least the C<$which> value
313 of C<CLOCK_REALTIME>, see L</clock_gettime>.
319 use Time::HiRes qw(usleep ualarm gettimeofday tv_interval);
321 $microseconds = 750_000;
322 usleep($microseconds);
324 # signal alarm in 2.5s & every .1s thereafter
325 ualarm(2_500_000, 100_000);
327 # get seconds and microseconds since the epoch
328 ($s, $usec) = gettimeofday();
330 # measure elapsed time
331 # (could also do by subtracting 2 gettimeofday return values)
332 $t0 = [gettimeofday];
333 # do bunch of stuff here
334 $t1 = [gettimeofday];
336 $t0_t1 = tv_interval $t0, $t1;
338 $elapsed = tv_interval ($t0, [gettimeofday]);
339 $elapsed = tv_interval ($t0); # equivalent code
342 # replacements for time, alarm and sleep that know about
346 $now_fractions = Time::HiRes::time;
347 Time::HiRes::sleep (2.5);
348 Time::HiRes::alarm (10.6666666);
350 use Time::HiRes qw ( time alarm sleep );
351 $now_fractions = time;
355 # Arm an interval timer to go off first at 10 seconds and
356 # after that every 2.5 seconds, in process virtual time
358 use Time::HiRes qw ( setitimer ITIMER_VIRTUAL time );
360 $SIG{VTALRM} = sub { print time, "\n" };
361 setitimer(ITIMER_VIRTUAL, 10, 2.5);
363 use Time::HiRes qw( clock_gettime clock_getres CLOCK_REALTIME );
364 # Read the POSIX high resolution timer.
365 my $high = clock_getres(CLOCK_REALTIME);
366 # But how accurate we can be, really?
367 my $reso = clock_getres(CLOCK_REALTIME);
371 In addition to the perl API described above, a C API is available for
372 extension writers. The following C functions are available in the
376 --------------- ----------------------
377 Time::NVtime double (*)()
378 Time::U2time void (*)(pTHX_ UV ret[2])
380 Both functions return equivalent information (like C<gettimeofday>)
381 but with different representations. The names C<NVtime> and C<U2time>
382 were selected mainly because they are operating system independent.
383 (C<gettimeofday> is Unix-centric, though some platforms like Win32 and
384 VMS have emulations for it.)
386 Here is an example of using C<NVtime> from C:
388 double (*myNVtime)(); /* Returns -1 on failure. */
389 SV **svp = hv_fetch(PL_modglobal, "Time::NVtime", 12, 0);
390 if (!svp) croak("Time::HiRes is required");
391 if (!SvIOK(*svp)) croak("Time::NVtime isn't a function pointer");
392 myNVtime = INT2PTR(double(*)(), SvIV(*svp));
393 printf("The current time is: %f\n", (*myNVtime)());
397 =head2 negative time not invented yet
399 You tried to use a negative time argument.
401 =head2 internal error: useconds < 0 (unsigned ... signed ...)
403 Something went horribly wrong-- the number of microseconds that cannot
404 become negative just became negative. Maybe your compiler is broken?
408 Notice that the core C<time()> maybe rounding rather than truncating.
409 What this means is that the core C<time()> may be reporting the time
410 as one second later than C<gettimeofday()> and C<Time::HiRes::time()>.
412 Adjusting the system clock (either manually or by services like ntp)
413 may cause problems, especially for long running programs that assume
414 a monotonously increasing time (note that all platforms do not adjust
415 time as gracefully as UNIX ntp does). For example in Win32 (and derived
416 platforms like Cygwin and MinGW) the Time::HiRes::time() may temporarily
417 drift off from the system clock (and the original time()) by up to 0.5
418 seconds. Time::HiRes will notice this eventually and recalibrate.
419 Note that since Time::HiRes 1.77 the clock_gettime(CLOCK_MONOTONIC)
420 might help in this (in case your system supports CLOCK_MONOTONIC).
424 Perl modules L<BSD::Resource>, L<Time::TAI64>.
426 Your system documentation for C<clock_gettime>, C<clock_settime>,
427 C<gettimeofday>, C<getitimer>, C<setitimer>, C<ualarm>.
431 D. Wegscheid <wegscd@whirlpool.com>
432 R. Schertler <roderick@argon.org>
433 J. Hietaniemi <jhi@iki.fi>
434 G. Aas <gisle@aas.no>
436 =head1 COPYRIGHT AND LICENSE
438 Copyright (c) 1996-2002 Douglas E. Wegscheid. All rights reserved.
440 Copyright (c) 2002, 2003, 2004, 2005 Jarkko Hietaniemi. All rights reserved.
442 This program is free software; you can redistribute it and/or modify
443 it under the same terms as Perl itself.