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