This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Typo fixes from Robin Houston in
[perl5.git] / ext / Time / HiRes / HiRes.pm
CommitLineData
dcf686c9
JH
1package Time::HiRes;
2
3use strict;
105cd853 4use vars qw($VERSION $XS_VERSION @ISA @EXPORT @EXPORT_OK $AUTOLOAD);
dcf686c9
JH
5
6require Exporter;
3f2ee006 7require DynaLoader;
dcf686c9 8
0cf8ddea 9@ISA = qw(Exporter DynaLoader);
dcf686c9
JH
10
11@EXPORT = qw( );
3c72ec00 12@EXPORT_OK = qw (usleep sleep ualarm alarm gettimeofday time tv_interval
ced84e60
SP
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
3f2ee006
HS
16 ITIMER_REAL ITIMER_VIRTUAL ITIMER_PROF ITIMER_REALPROF
17 d_usleep d_ualarm d_gettimeofday d_getitimer d_setitimer
ced84e60 18 d_nanosleep d_clock_gettime d_clock_getres);
3f2ee006 19
a5929ff3 20$VERSION = '1.83';
105cd853
YST
21$XS_VERSION = $VERSION;
22$VERSION = eval $VERSION;
3c72ec00
JH
23
24sub AUTOLOAD {
25 my $constname;
98b50af3 26 ($constname = $AUTOLOAD) =~ s/.*:://;
ced84e60 27 # print "AUTOLOAD: constname = $constname ($AUTOLOAD)\n";
98b50af3
JH
28 die "&Time::HiRes::constant not defined" if $constname eq 'constant';
29 my ($error, $val) = constant($constname);
ced84e60 30 # print "AUTOLOAD: error = $error, val = $val\n";
0cf8ddea
RGS
31 if ($error) {
32 my (undef,$file,$line) = caller;
33 die "$error at $file line $line.\n";
34 }
3c72ec00
JH
35 {
36 no strict 'refs';
37 *$AUTOLOAD = sub { $val };
38 }
39 goto &$AUTOLOAD;
40}
dcf686c9 41
ced84e60
SP
42sub import {
43 my $this = shift;
44 for my $i (@_) {
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)) {
50 require Carp;
51 Carp::croak("Time::HiRes::$i(): unimplemented in this platform");
52 }
53 }
54 Time::HiRes->export_to_level(1, $this, @_);
55}
56
0cf8ddea 57bootstrap Time::HiRes;
dcf686c9
JH
58
59# Preloaded methods go here.
60
61sub tv_interval {
62 # probably could have been done in C
63 my ($a, $b) = @_;
64 $b = [gettimeofday()] unless defined($b);
65 (${$b}[0] - ${$a}[0]) + ((${$b}[1] - ${$a}[1]) / 1_000_000);
66}
67
dcf686c9
JH
68# Autoload methods go after =cut, and are processed by the autosplit program.
69
701;
71__END__
72
73=head1 NAME
74
f7916ddb 75Time::HiRes - High resolution alarm, sleep, gettimeofday, interval timers
dcf686c9
JH
76
77=head1 SYNOPSIS
78
ced84e60
SP
79 use Time::HiRes qw( usleep ualarm gettimeofday tv_interval nanosleep
80 clock_gettime clock_getres );
dcf686c9
JH
81
82 usleep ($microseconds);
44d3ce20 83 nanosleep ($nanoseconds);
dcf686c9
JH
84
85 ualarm ($microseconds);
86 ualarm ($microseconds, $interval_microseconds);
87
88 $t0 = [gettimeofday];
89 ($seconds, $microseconds) = gettimeofday;
90
91 $elapsed = tv_interval ( $t0, [$seconds, $microseconds]);
92 $elapsed = tv_interval ( $t0, [gettimeofday]);
93 $elapsed = tv_interval ( $t0 );
94
95 use Time::HiRes qw ( time alarm sleep );
3c72ec00 96
dcf686c9
JH
97 $now_fractions = time;
98 sleep ($floating_seconds);
99 alarm ($floating_seconds);
100 alarm ($floating_seconds, $floating_interval);
101
3c72ec00 102 use Time::HiRes qw( setitimer getitimer
3f2ee006 103 ITIMER_REAL ITIMER_VIRTUAL ITIMER_PROF ITIMER_REALPROF );
3c72ec00
JH
104
105 setitimer ($which, $floating_seconds, $floating_interval );
106 getitimer ($which);
107
82cbdcc3
SP
108 $realtime = clock_gettime(CLOCK_REALTIME);
109 $resolution = clock_getres(CLOCK_REALTIME);
ced84e60 110
dcf686c9
JH
111=head1 DESCRIPTION
112
4ed0e2d4 113The C<Time::HiRes> module implements a Perl interface to the
44d3ce20
RGS
114C<usleep>, C<nanosleep>, C<ualarm>, C<gettimeofday>, and
115C<setitimer>/C<getitimer> system calls, in other words, high
116resolution time and timers. See the L</EXAMPLES> section below and the
117test scripts for usage; see your system documentation for the
118description of the underlying C<nanosleep> or C<usleep>, C<ualarm>,
119C<gettimeofday>, and C<setitimer>/C<getitimer> calls.
dcf686c9 120
6937b144 121If your system lacks C<gettimeofday()> or an emulation of it you don't
4ed0e2d4 122get C<gettimeofday()> or the one-argument form of C<tv_interval()>.
82cbdcc3
SP
123If your system lacks all of C<nanosleep()>, C<usleep()>,
124C<select()>, and C<poll>, you don't get C<Time::HiRes::usleep()>,
125C<Time::HiRes::nanosleep()>, or C<Time::HiRes::sleep()>.
126If your system lacks both C<ualarm()> and C<setitimer()> you don't get
44d3ce20 127C<Time::HiRes::ualarm()> or C<Time::HiRes::alarm()>.
3f2ee006
HS
128
129If you try to import an unimplemented function in the C<use> statement
130it will fail at compile time.
131
4ed0e2d4
RGS
132If your subsecond sleeping is implemented with C<nanosleep()> instead
133of C<usleep()>, you can mix subsecond sleeping with signals since
64a7a97c
RGS
134C<nanosleep()> does not use signals. This, however, is not portable,
135and you should first check for the truth value of
4ed0e2d4
RGS
136C<&Time::HiRes::d_nanosleep> to see whether you have nanosleep, and
137then carefully read your C<nanosleep()> C API documentation for any
44d3ce20 138peculiarities.
0be47ac6 139
0cf8ddea
RGS
140If you are using C<nanosleep> for something else than mixing sleeping
141with signals, give some thought to whether Perl is the tool you should
142be using for work requiring nanosecond accuracies.
dcf686c9 143
3c72ec00
JH
144The following functions can be imported from this module.
145No functions are exported by default.
dcf686c9
JH
146
147=over 4
148
149=item gettimeofday ()
150
0be47ac6 151In array context returns a two-element array with the seconds and
f7916ddb 152microseconds since the epoch. In scalar context returns floating
6937b144 153seconds like C<Time::HiRes::time()> (see below).
dcf686c9
JH
154
155=item usleep ( $useconds )
156
44d3ce20
RGS
157Sleeps for the number of microseconds (millionths of a second)
158specified. Returns the number of microseconds actually slept. Can
159sleep for more than one second, unlike the C<usleep> system call. See
160also C<Time::HiRes::usleep()> and C<Time::HiRes::sleep()>.
161
162Do not expect usleep() to be exact down to one microsecond.
163
164=item nanosleep ( $nanoseconds )
165
166Sleeps for the number of nanoseconds (1e9ths of a second) specified.
167Returns the number of nanoseconds actually slept (accurate only to
168microseconds, the nearest thousand of them). Can sleep for more than
169one second. See also C<Time::HiRes::sleep()> and
170C<Time::HiRes::usleep()>.
171
172Do not expect nanosleep() to be exact down to one nanosecond.
173Getting even accuracy of one thousand nanoseconds is good.
dcf686c9
JH
174
175=item ualarm ( $useconds [, $interval_useconds ] )
176
6937b144
MJD
177Issues a C<ualarm> call; the C<$interval_useconds> is optional and
178will be zero if unspecified, resulting in C<alarm>-like behaviour.
dcf686c9 179
993164ab 180Note that the interaction between alarms and sleeps is unspecified.
64a7a97c 181
443572f5
RB
182=item tv_interval
183
0be47ac6 184tv_interval ( $ref_to_gettimeofday [, $ref_to_later_gettimeofday] )
dcf686c9 185
f7916ddb 186Returns the floating seconds between the two times, which should have
6937b144 187been returned by C<gettimeofday()>. If the second argument is omitted,
f7916ddb 188then the current time is used.
dcf686c9
JH
189
190=item time ()
191
f7916ddb 192Returns a floating seconds since the epoch. This function can be
6937b144
MJD
193imported, resulting in a nice drop-in replacement for the C<time>
194provided with core Perl; see the L</EXAMPLES> below.
dcf686c9 195
6937b144
MJD
196B<NOTE 1>: This higher resolution timer can return values either less
197or more than the core C<time()>, depending on whether your platform
198rounds the higher resolution timer values up, down, or to the nearest second
199to get the core C<time()>, but naturally the difference should be never
ced84e60
SP
200more than half a second. See also L</clock_getres>, if available
201in your system.
f7916ddb 202
6937b144
MJD
203B<NOTE 2>: Since Sunday, September 9th, 2001 at 01:46:40 AM GMT, when
204the C<time()> seconds since epoch rolled over to 1_000_000_000, the
0be47ac6
JH
205default floating point format of Perl and the seconds since epoch have
206conspired to produce an apparent bug: if you print the value of
4ed0e2d4
RGS
207C<Time::HiRes::time()> you seem to be getting only five decimals, not
208six as promised (microseconds). Not to worry, the microseconds are
64a7a97c 209there (assuming your platform supports such granularity in the first
4ed0e2d4
RGS
210place). What is going on is that the default floating point format of
211Perl only outputs 15 digits. In this case that means ten digits
212before the decimal separator and five after. To see the microseconds
213you can use either C<printf>/C<sprintf> with C<"%.6f">, or the
214C<gettimeofday()> function in list context, which will give you the
215seconds and microseconds as two separate values.
389199d8 216
dcf686c9
JH
217=item sleep ( $floating_seconds )
218
f7916ddb 219Sleeps for the specified amount of seconds. Returns the number of
64a7a97c
RGS
220seconds actually slept (a floating point value). This function can
221be imported, resulting in a nice drop-in replacement for the C<sleep>
6937b144 222provided with perl, see the L</EXAMPLES> below.
dcf686c9 223
993164ab 224Note that the interaction between alarms and sleeps is unspecified.
64a7a97c 225
dcf686c9
JH
226=item alarm ( $floating_seconds [, $interval_floating_seconds ] )
227
6937b144
MJD
228The C<SIGALRM> signal is sent after the specified number of seconds.
229Implemented using C<ualarm()>. The C<$interval_floating_seconds> argument
230is optional and will be zero if unspecified, resulting in C<alarm()>-like
dcf686c9 231behaviour. This function can be imported, resulting in a nice drop-in
6937b144 232replacement for the C<alarm> provided with perl, see the L</EXAMPLES> below.
dcf686c9 233
64a7a97c
RGS
234B<NOTE 1>: With some combinations of operating systems and Perl
235releases C<SIGALRM> restarts C<select()>, instead of interrupting it.
236This means that an C<alarm()> followed by a C<select()> may together
237take the sum of the times specified for the the C<alarm()> and the
238C<select()>, not just the time of the C<alarm()>.
239
993164ab 240Note that the interaction between alarms and sleeps is unspecified.
3f2ee006 241
6937b144 242=item setitimer ( $which, $floating_seconds [, $interval_floating_seconds ] )
3c72ec00 243
09fa32a4 244Start up an interval timer: after a certain time, a signal arrives,
64a7a97c
RGS
245and more signals may keep arriving at certain intervals. To disable
246an "itimer", use C<$floating_seconds> of zero. If the
247C<$interval_floating_seconds> is set to zero (or unspecified), the
248timer is disabled B<after> the next delivered signal.
3c72ec00 249
6937b144
MJD
250Use of interval timers may interfere with C<alarm()>, C<sleep()>,
251and C<usleep()>. In standard-speak the "interaction is unspecified",
0be47ac6 252which means that I<anything> may happen: it may work, it may not.
3c72ec00
JH
253
254In scalar context, the remaining time in the timer is returned.
255
256In list context, both the remaining time and the interval are returned.
257
4ed0e2d4
RGS
258There are usually three or four interval timers available: the
259C<$which> can be C<ITIMER_REAL>, C<ITIMER_VIRTUAL>, C<ITIMER_PROF>, or
260C<ITIMER_REALPROF>. Note that which ones are available depends: true
261UNIX platforms usually have the first three, but (for example) Win32
262and Cygwin have only C<ITIMER_REAL>, and only Solaris seems to have
263C<ITIMER_REALPROF> (which is used to profile multithreaded programs).
3c72ec00 264
993164ab 265C<ITIMER_REAL> results in C<alarm()>-like behaviour. Time is counted in
6937b144 266I<real time>; that is, wallclock time. C<SIGALRM> is delivered when
3c72ec00
JH
267the timer expires.
268
4ed0e2d4
RGS
269C<ITIMER_VIRTUAL> counts time in (process) I<virtual time>; that is,
270only when the process is running. In multiprocessor/user/CPU systems
271this may be more or less than real or wallclock time. (This time is
272also known as the I<user time>.) C<SIGVTALRM> is delivered when the
273timer expires.
3c72ec00 274
6937b144 275C<ITIMER_PROF> counts time when either the process virtual time or when
0be47ac6
JH
276the 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
6937b144
MJD
278time and system time is known as the I<CPU time>.) C<SIGPROF> is
279delivered when the timer expires. C<SIGPROF> can interrupt system calls.
3c72ec00
JH
280
281The semantics of interval timers for multithreaded programs are
282system-specific, and some systems may support additional interval
6937b144 283timers. See your C<setitimer()> documentation.
3c72ec00
JH
284
285=item getitimer ( $which )
286
6937b144 287Return the remaining time in the interval timer specified by C<$which>.
3c72ec00
JH
288
289In scalar context, the remaining time is returned.
290
291In list context, both the remaining time and the interval are returned.
6937b144 292The interval is always what you put in using C<setitimer()>.
3c72ec00 293
ced84e60
SP
294=item clock_gettime ( $which )
295
296Return as seconds the current value of the POSIX high resolution timer
297specified by C<$which>. All implementations that support POSIX high
298resolution timers are supposed to support at least the C<$which> value
299of C<CLOCK_REALTIME>, which is supposed to return results close to the
300results of C<gettimeofday>, or the number of seconds since 00:00:00:00
301January 1, 1970 Greenwich Mean Time (GMT). Do not assume that
302CLOCK_REALTIME is zero, it might be one, or something else.
303Another potentially useful (but not available everywhere) value is
304C<CLOCK_MONOTONIC>, which guarantees a monotonically increasing time
305value (unlike time(), which can be adjusted). See your system
306documentation for other possibly supported values.
307
308=item clock_getres ( $which )
309
310Return as seconds the resolution of the POSIX high resolution timer
311specified by C<$which>. All implementations that support POSIX high
312resolution timers are supposed to support at least the C<$which> value
313of C<CLOCK_REALTIME>, see L</clock_gettime>.
314
dcf686c9
JH
315=back
316
317=head1 EXAMPLES
318
319 use Time::HiRes qw(usleep ualarm gettimeofday tv_interval);
320
321 $microseconds = 750_000;
70cf0185 322 usleep($microseconds);
dcf686c9
JH
323
324 # signal alarm in 2.5s & every .1s thereafter
70cf0185 325 ualarm(2_500_000, 100_000);
dcf686c9
JH
326
327 # get seconds and microseconds since the epoch
70cf0185 328 ($s, $usec) = gettimeofday();
dcf686c9
JH
329
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];
335 # do more stuff here
336 $t0_t1 = tv_interval $t0, $t1;
0be47ac6 337
dcf686c9
JH
338 $elapsed = tv_interval ($t0, [gettimeofday]);
339 $elapsed = tv_interval ($t0); # equivalent code
340
341 #
342 # replacements for time, alarm and sleep that know about
343 # floating seconds
344 #
345 use Time::HiRes;
346 $now_fractions = Time::HiRes::time;
347 Time::HiRes::sleep (2.5);
348 Time::HiRes::alarm (10.6666666);
0be47ac6 349
dcf686c9
JH
350 use Time::HiRes qw ( time alarm sleep );
351 $now_fractions = time;
352 sleep (2.5);
353 alarm (10.6666666);
354
3c72ec00
JH
355 # Arm an interval timer to go off first at 10 seconds and
356 # after that every 2.5 seconds, in process virtual time
357
358 use Time::HiRes qw ( setitimer ITIMER_VIRTUAL time );
359
36d6c396 360 $SIG{VTALRM} = sub { print time, "\n" };
3c72ec00
JH
361 setitimer(ITIMER_VIRTUAL, 10, 2.5);
362
1a7d3a53
SP
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);
ced84e60 368
dcf686c9
JH
369=head1 C API
370
371In addition to the perl API described above, a C API is available for
372extension writers. The following C functions are available in the
373modglobal hash:
374
375 name C prototype
376 --------------- ----------------------
377 Time::NVtime double (*)()
06252d99 378 Time::U2time void (*)(pTHX_ UV ret[2])
dcf686c9 379
6937b144
MJD
380Both functions return equivalent information (like C<gettimeofday>)
381but with different representations. The names C<NVtime> and C<U2time>
dcf686c9 382were selected mainly because they are operating system independent.
56c1b3bd
RGS
383(C<gettimeofday> is Unix-centric, though some platforms like Win32 and
384VMS have emulations for it.)
dcf686c9 385
6937b144 386Here is an example of using C<NVtime> from C:
dcf686c9 387
993164ab 388 double (*myNVtime)(); /* Returns -1 on failure. */
dcf686c9
JH
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");
356234a5 392 myNVtime = INT2PTR(double(*)(), SvIV(*svp));
dcf686c9
JH
393 printf("The current time is: %f\n", (*myNVtime)());
394
db0b859f
JH
395=head1 DIAGNOSTICS
396
397=head2 negative time not invented yet
398
399You tried to use a negative time argument.
400
401=head2 internal error: useconds < 0 (unsigned ... signed ...)
402
403Something went horribly wrong-- the number of microseconds that cannot
404become negative just became negative. Maybe your compiler is broken?
405
f03b998d
JH
406=head1 CAVEATS
407
6937b144 408Notice that the core C<time()> maybe rounding rather than truncating.
d8cb5b61
RGS
409What this means is that the core C<time()> may be reporting the time
410as one second later than C<gettimeofday()> and C<Time::HiRes::time()>.
411
412Adjusting the system clock (either manually or by services like ntp)
413may cause problems, especially for long running programs that assume
414a monotonously increasing time (note that all platforms do not adjust
415time as gracefully as UNIX ntp does). For example in Win32 (and derived
416platforms like Cygwin and MinGW) the Time::HiRes::time() may temporarily
417drift off from the system clock (and the original time()) by up to 0.5
418seconds. Time::HiRes will notice this eventually and recalibrate.
ced84e60 419Note that since Time::HiRes 1.77 the clock_gettime(CLOCK_MONOTONIC)
1a7d3a53 420might help in this (in case your system supports CLOCK_MONOTONIC).
f03b998d 421
26e22fd9
RGS
422=head1 SEE ALSO
423
ced84e60
SP
424Perl modules L<BSD::Resource>, L<Time::TAI64>.
425
426Your system documentation for C<clock_gettime>, C<clock_settime>,
427C<gettimeofday>, C<getitimer>, C<setitimer>, C<ualarm>.
26e22fd9 428
dcf686c9
JH
429=head1 AUTHORS
430
431D. Wegscheid <wegscd@whirlpool.com>
432R. Schertler <roderick@argon.org>
433J. Hietaniemi <jhi@iki.fi>
434G. Aas <gisle@aas.no>
435
3f2ee006 436=head1 COPYRIGHT AND LICENSE
dcf686c9 437
3f2ee006 438Copyright (c) 1996-2002 Douglas E. Wegscheid. All rights reserved.
dcf686c9 439
0cf8ddea 440Copyright (c) 2002, 2003, 2004, 2005 Jarkko Hietaniemi. All rights reserved.
dcf686c9 441
3f2ee006
HS
442This program is free software; you can redistribute it and/or modify
443it under the same terms as Perl itself.
dcf686c9
JH
444
445=cut