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