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