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