This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Update Time-HiRes to CPAN version 1.9742
[perl5.git] / dist / Time-HiRes / HiRes.pm
CommitLineData
dcf686c9
JH
1package Time::HiRes;
2
90e44bf6 3{ use 5.006; }
dcf686c9 4use strict;
dcf686c9
JH
5
6require Exporter;
3f2ee006 7require DynaLoader;
dcf686c9 8
90e44bf6 9our @ISA = qw(Exporter DynaLoader);
dcf686c9 10
90e44bf6
Z
11our @EXPORT = qw( );
12our @EXPORT_OK = qw (usleep sleep ualarm alarm gettimeofday time tv_interval
ced84e60 13 getitimer setitimer nanosleep clock_gettime clock_getres
170c5524 14 clock clock_nanosleep
0915f2cb
JH
15 CLOCK_BOOTTIME CLOCK_HIGHRES
16 CLOCK_MONOTONIC CLOCK_MONOTONIC_COARSE
17 CLOCK_MONOTONIC_PRECISE CLOCK_MONOTONIC_RAW
18 CLOCK_PROCESS_CPUTIME_ID
19 CLOCK_REALTIME CLOCK_REALTIME_COARSE
20 CLOCK_REALTIME_FAST CLOCK_REALTIME_PRECISE
21 CLOCK_SECOND CLOCK_SOFTTIME CLOCK_THREAD_CPUTIME_ID
170c5524 22 CLOCK_TIMEOFDAY CLOCKS_PER_SEC
3f2ee006 23 ITIMER_REAL ITIMER_VIRTUAL ITIMER_PROF ITIMER_REALPROF
170c5524 24 TIMER_ABSTIME
3f2ee006 25 d_usleep d_ualarm d_gettimeofday d_getitimer d_setitimer
c4a535af 26 d_nanosleep d_clock_gettime d_clock_getres d_hires_utime
75d5269b 27 d_clock d_clock_nanosleep
c4a535af 28 stat lstat utime
75d5269b 29 );
bf8300de 30
5cd155b0 31our $VERSION = '1.9742';
90e44bf6 32our $XS_VERSION = $VERSION;
105cd853 33$VERSION = eval $VERSION;
3c72ec00 34
90e44bf6 35our $AUTOLOAD;
3c72ec00
JH
36sub AUTOLOAD {
37 my $constname;
98b50af3 38 ($constname = $AUTOLOAD) =~ s/.*:://;
ced84e60 39 # print "AUTOLOAD: constname = $constname ($AUTOLOAD)\n";
98b50af3
JH
40 die "&Time::HiRes::constant not defined" if $constname eq 'constant';
41 my ($error, $val) = constant($constname);
ced84e60 42 # print "AUTOLOAD: error = $error, val = $val\n";
0cf8ddea
RGS
43 if ($error) {
44 my (undef,$file,$line) = caller;
45 die "$error at $file line $line.\n";
46 }
3c72ec00
JH
47 {
48 no strict 'refs';
49 *$AUTOLOAD = sub { $val };
50 }
51 goto &$AUTOLOAD;
52}
dcf686c9 53
ced84e60
SP
54sub import {
55 my $this = shift;
56 for my $i (@_) {
170c5524
SP
57 if (($i eq 'clock_getres' && !&d_clock_getres) ||
58 ($i eq 'clock_gettime' && !&d_clock_gettime) ||
59 ($i eq 'clock_nanosleep' && !&d_clock_nanosleep) ||
60 ($i eq 'clock' && !&d_clock) ||
61 ($i eq 'nanosleep' && !&d_nanosleep) ||
62 ($i eq 'usleep' && !&d_usleep) ||
c4a535af 63 ($i eq 'utime' && !&d_hires_utime) ||
170c5524 64 ($i eq 'ualarm' && !&d_ualarm)) {
ced84e60
SP
65 require Carp;
66 Carp::croak("Time::HiRes::$i(): unimplemented in this platform");
67 }
68 }
69 Time::HiRes->export_to_level(1, $this, @_);
70}
71
0cf8ddea 72bootstrap Time::HiRes;
dcf686c9
JH
73
74# Preloaded methods go here.
75
76sub tv_interval {
77 # probably could have been done in C
78 my ($a, $b) = @_;
79 $b = [gettimeofday()] unless defined($b);
80 (${$b}[0] - ${$a}[0]) + ((${$b}[1] - ${$a}[1]) / 1_000_000);
81}
82
dcf686c9
JH
83# Autoload methods go after =cut, and are processed by the autosplit program.
84
851;
86__END__
87
88=head1 NAME
89
f7916ddb 90Time::HiRes - High resolution alarm, sleep, gettimeofday, interval timers
dcf686c9
JH
91
92=head1 SYNOPSIS
93
ced84e60 94 use Time::HiRes qw( usleep ualarm gettimeofday tv_interval nanosleep
75d5269b 95 clock_gettime clock_getres clock_nanosleep clock
c4a535af 96 stat lstat utime);
dcf686c9
JH
97
98 usleep ($microseconds);
44d3ce20 99 nanosleep ($nanoseconds);
dcf686c9
JH
100
101 ualarm ($microseconds);
102 ualarm ($microseconds, $interval_microseconds);
103
104 $t0 = [gettimeofday];
105 ($seconds, $microseconds) = gettimeofday;
106
107 $elapsed = tv_interval ( $t0, [$seconds, $microseconds]);
108 $elapsed = tv_interval ( $t0, [gettimeofday]);
109 $elapsed = tv_interval ( $t0 );
110
111 use Time::HiRes qw ( time alarm sleep );
3c72ec00 112
dcf686c9
JH
113 $now_fractions = time;
114 sleep ($floating_seconds);
115 alarm ($floating_seconds);
116 alarm ($floating_seconds, $floating_interval);
117
bfe77af1 118 use Time::HiRes qw( setitimer getitimer );
3c72ec00
JH
119
120 setitimer ($which, $floating_seconds, $floating_interval );
121 getitimer ($which);
122
bfe77af1 123 use Time::HiRes qw( clock_gettime clock_getres clock_nanosleep
e46aa1dd
KW
124 ITIMER_REAL ITIMER_VIRTUAL ITIMER_PROF
125 ITIMER_REALPROF );
bfe77af1 126
82cbdcc3
SP
127 $realtime = clock_gettime(CLOCK_REALTIME);
128 $resolution = clock_getres(CLOCK_REALTIME);
ced84e60 129
a8fb48f7
SP
130 clock_nanosleep(CLOCK_REALTIME, 1.5e9);
131 clock_nanosleep(CLOCK_REALTIME, time()*1e9 + 10e9, TIMER_ABSTIME);
170c5524
SP
132
133 my $ticktock = clock();
134
0f0eae2c 135 use Time::HiRes qw( stat lstat );
bfe77af1 136
c09e847b 137 my @stat = stat("file");
75d5269b 138 my @stat = stat(FH);
0f0eae2c 139 my @stat = lstat("file");
75d5269b 140
c4a535af
SH
141 use Time::HiRes qw( utime );
142 utime $floating_seconds, $floating_seconds, file...;
143
dcf686c9
JH
144=head1 DESCRIPTION
145
4ed0e2d4 146The C<Time::HiRes> module implements a Perl interface to the
44d3ce20
RGS
147C<usleep>, C<nanosleep>, C<ualarm>, C<gettimeofday>, and
148C<setitimer>/C<getitimer> system calls, in other words, high
149resolution time and timers. See the L</EXAMPLES> section below and the
150test scripts for usage; see your system documentation for the
151description of the underlying C<nanosleep> or C<usleep>, C<ualarm>,
152C<gettimeofday>, and C<setitimer>/C<getitimer> calls.
dcf686c9 153
6937b144 154If your system lacks C<gettimeofday()> or an emulation of it you don't
4ed0e2d4 155get C<gettimeofday()> or the one-argument form of C<tv_interval()>.
82cbdcc3
SP
156If your system lacks all of C<nanosleep()>, C<usleep()>,
157C<select()>, and C<poll>, you don't get C<Time::HiRes::usleep()>,
158C<Time::HiRes::nanosleep()>, or C<Time::HiRes::sleep()>.
159If your system lacks both C<ualarm()> and C<setitimer()> you don't get
44d3ce20 160C<Time::HiRes::ualarm()> or C<Time::HiRes::alarm()>.
3f2ee006
HS
161
162If you try to import an unimplemented function in the C<use> statement
163it will fail at compile time.
164
4ed0e2d4
RGS
165If your subsecond sleeping is implemented with C<nanosleep()> instead
166of C<usleep()>, you can mix subsecond sleeping with signals since
64a7a97c
RGS
167C<nanosleep()> does not use signals. This, however, is not portable,
168and you should first check for the truth value of
4ed0e2d4
RGS
169C<&Time::HiRes::d_nanosleep> to see whether you have nanosleep, and
170then carefully read your C<nanosleep()> C API documentation for any
44d3ce20 171peculiarities.
0be47ac6 172
0cf8ddea
RGS
173If you are using C<nanosleep> for something else than mixing sleeping
174with signals, give some thought to whether Perl is the tool you should
175be using for work requiring nanosecond accuracies.
dcf686c9 176
bfe77af1
SP
177Remember that unless you are working on a I<hard realtime> system,
178any clocks and timers will be imprecise, especially so if you are working
179in a pre-emptive multiuser system. Understand the difference between
180I<wallclock time> and process time (in UNIX-like systems the sum of
181I<user> and I<system> times). Any attempt to sleep for X seconds will
0f0eae2c 182most probably end up sleeping B<more> than that, but don't be surprised
bfe77af1
SP
183if you end up sleeping slightly B<less>.
184
3c72ec00
JH
185The following functions can be imported from this module.
186No functions are exported by default.
dcf686c9
JH
187
188=over 4
189
190=item gettimeofday ()
191
0be47ac6 192In array context returns a two-element array with the seconds and
f7916ddb 193microseconds since the epoch. In scalar context returns floating
6937b144 194seconds like C<Time::HiRes::time()> (see below).
dcf686c9
JH
195
196=item usleep ( $useconds )
197
44d3ce20 198Sleeps for the number of microseconds (millionths of a second)
bfe77af1
SP
199specified. Returns the number of microseconds actually slept.
200Can sleep for more than one second, unlike the C<usleep> system call.
201Can also sleep for zero seconds, which often works like a I<thread yield>.
170c5524
SP
202See also C<Time::HiRes::usleep()>, C<Time::HiRes::sleep()>, and
203C<Time::HiRes::clock_nanosleep()>.
44d3ce20
RGS
204
205Do not expect usleep() to be exact down to one microsecond.
206
207=item nanosleep ( $nanoseconds )
208
209Sleeps for the number of nanoseconds (1e9ths of a second) specified.
210Returns the number of nanoseconds actually slept (accurate only to
211microseconds, the nearest thousand of them). Can sleep for more than
bfe77af1
SP
212one second. Can also sleep for zero seconds, which often works like
213a I<thread yield>. See also C<Time::HiRes::sleep()>,
170c5524 214C<Time::HiRes::usleep()>, and C<Time::HiRes::clock_nanosleep()>.
44d3ce20
RGS
215
216Do not expect nanosleep() to be exact down to one nanosecond.
217Getting even accuracy of one thousand nanoseconds is good.
dcf686c9
JH
218
219=item ualarm ( $useconds [, $interval_useconds ] )
220
6937b144
MJD
221Issues a C<ualarm> call; the C<$interval_useconds> is optional and
222will be zero if unspecified, resulting in C<alarm>-like behaviour.
dcf686c9 223
bf8300de
RGS
224Returns the remaining time in the alarm in microseconds, or C<undef>
225if an error occurred.
226
bfe77af1
SP
227ualarm(0) will cancel an outstanding ualarm().
228
993164ab 229Note that the interaction between alarms and sleeps is unspecified.
64a7a97c 230
443572f5
RB
231=item tv_interval
232
0be47ac6 233tv_interval ( $ref_to_gettimeofday [, $ref_to_later_gettimeofday] )
dcf686c9 234
f7916ddb 235Returns the floating seconds between the two times, which should have
6937b144 236been returned by C<gettimeofday()>. If the second argument is omitted,
f7916ddb 237then the current time is used.
dcf686c9
JH
238
239=item time ()
240
f7916ddb 241Returns a floating seconds since the epoch. This function can be
6937b144
MJD
242imported, resulting in a nice drop-in replacement for the C<time>
243provided with core Perl; see the L</EXAMPLES> below.
dcf686c9 244
6937b144
MJD
245B<NOTE 1>: This higher resolution timer can return values either less
246or more than the core C<time()>, depending on whether your platform
247rounds the higher resolution timer values up, down, or to the nearest second
248to get the core C<time()>, but naturally the difference should be never
ced84e60
SP
249more than half a second. See also L</clock_getres>, if available
250in your system.
f7916ddb 251
6937b144
MJD
252B<NOTE 2>: Since Sunday, September 9th, 2001 at 01:46:40 AM GMT, when
253the C<time()> seconds since epoch rolled over to 1_000_000_000, the
0be47ac6
JH
254default floating point format of Perl and the seconds since epoch have
255conspired to produce an apparent bug: if you print the value of
4ed0e2d4
RGS
256C<Time::HiRes::time()> you seem to be getting only five decimals, not
257six as promised (microseconds). Not to worry, the microseconds are
64a7a97c 258there (assuming your platform supports such granularity in the first
4ed0e2d4
RGS
259place). What is going on is that the default floating point format of
260Perl only outputs 15 digits. In this case that means ten digits
261before the decimal separator and five after. To see the microseconds
262you can use either C<printf>/C<sprintf> with C<"%.6f">, or the
263C<gettimeofday()> function in list context, which will give you the
264seconds and microseconds as two separate values.
389199d8 265
dcf686c9
JH
266=item sleep ( $floating_seconds )
267
f7916ddb 268Sleeps for the specified amount of seconds. Returns the number of
64a7a97c
RGS
269seconds actually slept (a floating point value). This function can
270be imported, resulting in a nice drop-in replacement for the C<sleep>
6937b144 271provided with perl, see the L</EXAMPLES> below.
dcf686c9 272
993164ab 273Note that the interaction between alarms and sleeps is unspecified.
64a7a97c 274
dcf686c9
JH
275=item alarm ( $floating_seconds [, $interval_floating_seconds ] )
276
6937b144 277The C<SIGALRM> signal is sent after the specified number of seconds.
bf8300de
RGS
278Implemented using C<setitimer()> if available, C<ualarm()> if not.
279The C<$interval_floating_seconds> argument is optional and will be
280zero if unspecified, resulting in C<alarm()>-like behaviour. This
281function can be imported, resulting in a nice drop-in replacement for
282the C<alarm> provided with perl, see the L</EXAMPLES> below.
283
284Returns the remaining time in the alarm in seconds, or C<undef>
285if an error occurred.
dcf686c9 286
64a7a97c
RGS
287B<NOTE 1>: With some combinations of operating systems and Perl
288releases C<SIGALRM> restarts C<select()>, instead of interrupting it.
289This means that an C<alarm()> followed by a C<select()> may together
858dcda5 290take the sum of the times specified for the C<alarm()> and the
64a7a97c
RGS
291C<select()>, not just the time of the C<alarm()>.
292
993164ab 293Note that the interaction between alarms and sleeps is unspecified.
3f2ee006 294
6937b144 295=item setitimer ( $which, $floating_seconds [, $interval_floating_seconds ] )
3c72ec00 296
bfe77af1 297Start up an interval timer: after a certain time, a signal ($which) arrives,
64a7a97c
RGS
298and more signals may keep arriving at certain intervals. To disable
299an "itimer", use C<$floating_seconds> of zero. If the
300C<$interval_floating_seconds> is set to zero (or unspecified), the
301timer is disabled B<after> the next delivered signal.
3c72ec00 302
6937b144
MJD
303Use of interval timers may interfere with C<alarm()>, C<sleep()>,
304and C<usleep()>. In standard-speak the "interaction is unspecified",
0be47ac6 305which means that I<anything> may happen: it may work, it may not.
3c72ec00
JH
306
307In scalar context, the remaining time in the timer is returned.
308
309In list context, both the remaining time and the interval are returned.
310
bfe77af1 311There are usually three or four interval timers (signals) available: the
4ed0e2d4
RGS
312C<$which> can be C<ITIMER_REAL>, C<ITIMER_VIRTUAL>, C<ITIMER_PROF>, or
313C<ITIMER_REALPROF>. Note that which ones are available depends: true
e5620114
RGS
314UNIX platforms usually have the first three, but only Solaris seems to
315have C<ITIMER_REALPROF> (which is used to profile multithreaded programs).
0f0eae2c 316Win32 unfortunately does not have interval timers.
3c72ec00 317
993164ab 318C<ITIMER_REAL> results in C<alarm()>-like behaviour. Time is counted in
6937b144 319I<real time>; that is, wallclock time. C<SIGALRM> is delivered when
3c72ec00
JH
320the timer expires.
321
4ed0e2d4
RGS
322C<ITIMER_VIRTUAL> counts time in (process) I<virtual time>; that is,
323only when the process is running. In multiprocessor/user/CPU systems
324this may be more or less than real or wallclock time. (This time is
325also known as the I<user time>.) C<SIGVTALRM> is delivered when the
326timer expires.
3c72ec00 327
6937b144 328C<ITIMER_PROF> counts time when either the process virtual time or when
0be47ac6
JH
329the operating system is running on behalf of the process (such as I/O).
330(This time is also known as the I<system time>.) (The sum of user
6937b144
MJD
331time and system time is known as the I<CPU time>.) C<SIGPROF> is
332delivered when the timer expires. C<SIGPROF> can interrupt system calls.
3c72ec00
JH
333
334The semantics of interval timers for multithreaded programs are
335system-specific, and some systems may support additional interval
bfe77af1
SP
336timers. For example, it is unspecified which thread gets the signals.
337See your C<setitimer()> documentation.
3c72ec00
JH
338
339=item getitimer ( $which )
340
6937b144 341Return the remaining time in the interval timer specified by C<$which>.
3c72ec00
JH
342
343In scalar context, the remaining time is returned.
344
345In list context, both the remaining time and the interval are returned.
6937b144 346The interval is always what you put in using C<setitimer()>.
3c72ec00 347
ced84e60
SP
348=item clock_gettime ( $which )
349
350Return as seconds the current value of the POSIX high resolution timer
351specified by C<$which>. All implementations that support POSIX high
352resolution timers are supposed to support at least the C<$which> value
353of C<CLOCK_REALTIME>, which is supposed to return results close to the
354results of C<gettimeofday>, or the number of seconds since 00:00:00:00
355January 1, 1970 Greenwich Mean Time (GMT). Do not assume that
356CLOCK_REALTIME is zero, it might be one, or something else.
357Another potentially useful (but not available everywhere) value is
358C<CLOCK_MONOTONIC>, which guarantees a monotonically increasing time
e5620114
RGS
359value (unlike time() or gettimeofday(), which can be adjusted).
360See your system documentation for other possibly supported values.
ced84e60
SP
361
362=item clock_getres ( $which )
363
364Return as seconds the resolution of the POSIX high resolution timer
365specified by C<$which>. All implementations that support POSIX high
366resolution timers are supposed to support at least the C<$which> value
170c5524
SP
367of C<CLOCK_REALTIME>, see L</clock_gettime>.
368
98f12c0e
JH
369B<NOTE>: the resolution returned may be highly optimistic. Even if
370the resolution is high (a small number), all it means is that you'll
371be able to specify the arguments to clock_gettime() and clock_nanosleep()
372with that resolution. The system might not actually be able to measure
373events at that resolution, and the various overheads and the overall system
374load are certain to affect any timings.
375
a8fb48f7 376=item clock_nanosleep ( $which, $nanoseconds, $flags = 0)
170c5524 377
a8fb48f7
SP
378Sleeps for the number of nanoseconds (1e9ths of a second) specified.
379Returns the number of nanoseconds actually slept. The $which is the
170c5524
SP
380"clock id", as with clock_gettime() and clock_getres(). The flags
381default to zero but C<TIMER_ABSTIME> can specified (must be exported
382explicitly) which means that C<$nanoseconds> is not a time interval
383(as is the default) but instead an absolute time. Can sleep for more
384than one second. Can also sleep for zero seconds, which often works
385like a I<thread yield>. See also C<Time::HiRes::sleep()>,
386C<Time::HiRes::usleep()>, and C<Time::HiRes::nanosleep()>.
387
388Do not expect clock_nanosleep() to be exact down to one nanosecond.
389Getting even accuracy of one thousand nanoseconds is good.
390
391=item clock()
392
393Return as seconds the I<process time> (user + system time) spent by
394the process since the first call to clock() (the definition is B<not>
395"since the start of the process", though if you are lucky these times
396may be quite close to each other, depending on the system). What this
397means is that you probably need to store the result of your first call
398to clock(), and subtract that value from the following results of clock().
399
400The time returned also includes the process times of the terminated
401child processes for which wait() has been executed. This value is
402somewhat like the second value returned by the times() of core Perl,
403but not necessarily identical. Note that due to backward
ff7df920
SP
404compatibility limitations the returned value may wrap around at about
4052147 seconds or at about 36 minutes.
ced84e60 406
75d5269b
SP
407=item stat
408
409=item stat FH
410
411=item stat EXPR
412
0f0eae2c
Z
413=item lstat
414
415=item lstat FH
416
417=item lstat EXPR
418
419As L<perlfunc/stat> or L<perlfunc/lstat>
420but with the access/modify/change file timestamps
75d5269b
SP
421in subsecond resolution, if the operating system and the filesystem
422both support such timestamps. To override the standard stat():
423
424 use Time::HiRes qw(stat);
425
426Test for the value of &Time::HiRes::d_hires_stat to find out whether
427the operating system supports subsecond file timestamps: a value
428larger than zero means yes. There are unfortunately no easy
429ways to find out whether the filesystem supports such timestamps.
c09e847b
SP
430UNIX filesystems often do; NTFS does; FAT doesn't (FAT timestamp
431granularity is B<two> seconds).
75d5269b
SP
432
433A zero return value of &Time::HiRes::d_hires_stat means that
0f0eae2c
Z
434Time::HiRes::stat is a no-op passthrough for CORE::stat()
435(and likewise for lstat),
75d5269b 436and therefore the timestamps will stay integers. The same
bfe77af1 437thing will happen if the filesystem does not do subsecond timestamps,
c09e847b 438even if the &Time::HiRes::d_hires_stat is non-zero.
75d5269b
SP
439
440In any case do not expect nanosecond resolution, or even a microsecond
bfe77af1
SP
441resolution. Also note that the modify/access timestamps might have
442different resolutions, and that they need not be synchronized, e.g.
443if the operations are
444
445 write
446 stat # t1
447 read
448 stat # t2
449
450the access time stamp from t2 need not be greater-than the modify
451time stamp from t1: it may be equal or I<less>.
75d5269b 452
c4a535af
SH
453=item utime LIST
454
455As L<perlfunc/utime>
456but with the ability to set the access/modify file timestamps
457in subsecond resolution, if the operating system and the filesystem
458both support such timestamps. To override the standard utime():
459
460 use Time::HiRes qw(utime);
461
462Test for the value of &Time::HiRes::d_hires_utime to find out whether
463the operating system supports setting subsecond file timestamps.
464
465As with CORE::utime(), passing undef as both the atime and mtime will
466call the syscall with a NULL argument.
467
468The actual achievable subsecond resolution depends on the combination
469of the operating system and the filesystem.
470
471Returns the number of files successfully changed.
472
dcf686c9
JH
473=back
474
475=head1 EXAMPLES
476
477 use Time::HiRes qw(usleep ualarm gettimeofday tv_interval);
478
479 $microseconds = 750_000;
70cf0185 480 usleep($microseconds);
dcf686c9
JH
481
482 # signal alarm in 2.5s & every .1s thereafter
70cf0185 483 ualarm(2_500_000, 100_000);
bfe77af1
SP
484 # cancel that ualarm
485 ualarm(0);
dcf686c9
JH
486
487 # get seconds and microseconds since the epoch
70cf0185 488 ($s, $usec) = gettimeofday();
dcf686c9
JH
489
490 # measure elapsed time
491 # (could also do by subtracting 2 gettimeofday return values)
492 $t0 = [gettimeofday];
493 # do bunch of stuff here
494 $t1 = [gettimeofday];
495 # do more stuff here
496 $t0_t1 = tv_interval $t0, $t1;
0be47ac6 497
dcf686c9
JH
498 $elapsed = tv_interval ($t0, [gettimeofday]);
499 $elapsed = tv_interval ($t0); # equivalent code
500
501 #
502 # replacements for time, alarm and sleep that know about
503 # floating seconds
504 #
505 use Time::HiRes;
506 $now_fractions = Time::HiRes::time;
507 Time::HiRes::sleep (2.5);
508 Time::HiRes::alarm (10.6666666);
0be47ac6 509
dcf686c9
JH
510 use Time::HiRes qw ( time alarm sleep );
511 $now_fractions = time;
512 sleep (2.5);
513 alarm (10.6666666);
514
3c72ec00
JH
515 # Arm an interval timer to go off first at 10 seconds and
516 # after that every 2.5 seconds, in process virtual time
517
518 use Time::HiRes qw ( setitimer ITIMER_VIRTUAL time );
519
36d6c396 520 $SIG{VTALRM} = sub { print time, "\n" };
3c72ec00
JH
521 setitimer(ITIMER_VIRTUAL, 10, 2.5);
522
1a7d3a53
SP
523 use Time::HiRes qw( clock_gettime clock_getres CLOCK_REALTIME );
524 # Read the POSIX high resolution timer.
0f0eae2c 525 my $high = clock_gettime(CLOCK_REALTIME);
1a7d3a53
SP
526 # But how accurate we can be, really?
527 my $reso = clock_getres(CLOCK_REALTIME);
ced84e60 528
170c5524
SP
529 use Time::HiRes qw( clock_nanosleep TIMER_ABSTIME );
530 clock_nanosleep(CLOCK_REALTIME, 1e6);
531 clock_nanosleep(CLOCK_REALTIME, 2e9, TIMER_ABSTIME);
532
533 use Time::HiRes qw( clock );
534 my $clock0 = clock();
535 ... # Do something.
536 my $clock1 = clock();
537 my $clockd = $clock1 - $clock0;
538
c09e847b
SP
539 use Time::HiRes qw( stat );
540 my ($atime, $mtime, $ctime) = (stat("istics"))[8, 9, 10];
541
dcf686c9
JH
542=head1 C API
543
544In addition to the perl API described above, a C API is available for
545extension writers. The following C functions are available in the
546modglobal hash:
547
548 name C prototype
549 --------------- ----------------------
120b53f9 550 Time::NVtime NV (*)()
06252d99 551 Time::U2time void (*)(pTHX_ UV ret[2])
dcf686c9 552
6937b144
MJD
553Both functions return equivalent information (like C<gettimeofday>)
554but with different representations. The names C<NVtime> and C<U2time>
dcf686c9 555were selected mainly because they are operating system independent.
56c1b3bd
RGS
556(C<gettimeofday> is Unix-centric, though some platforms like Win32 and
557VMS have emulations for it.)
dcf686c9 558
6937b144 559Here is an example of using C<NVtime> from C:
dcf686c9 560
120b53f9 561 NV (*myNVtime)(); /* Returns -1 on failure. */
07e4dd7a 562 SV **svp = hv_fetchs(PL_modglobal, "Time::NVtime", 0);
dcf686c9
JH
563 if (!svp) croak("Time::HiRes is required");
564 if (!SvIOK(*svp)) croak("Time::NVtime isn't a function pointer");
120b53f9
RS
565 myNVtime = INT2PTR(NV(*)(), SvIV(*svp));
566 printf("The current time is: %" NVff "\n", (*myNVtime)());
dcf686c9 567
db0b859f
JH
568=head1 DIAGNOSTICS
569
34f69483
SP
570=head2 useconds or interval more than ...
571
572In ualarm() you tried to use number of microseconds or interval (also
573in microseconds) more than 1_000_000 and setitimer() is not available
574in your system to emulate that case.
575
db0b859f
JH
576=head2 negative time not invented yet
577
578You tried to use a negative time argument.
579
580=head2 internal error: useconds < 0 (unsigned ... signed ...)
581
582Something went horribly wrong-- the number of microseconds that cannot
583become negative just became negative. Maybe your compiler is broken?
584
bf8300de
RGS
585=head2 useconds or uinterval equal to or more than 1000000
586
587In some platforms it is not possible to get an alarm with subsecond
588resolution and later than one second.
589
590=head2 unimplemented in this platform
591
592Some calls simply aren't available, real or emulated, on every platform.
593
f03b998d
JH
594=head1 CAVEATS
595
6937b144 596Notice that the core C<time()> maybe rounding rather than truncating.
d8cb5b61
RGS
597What this means is that the core C<time()> may be reporting the time
598as one second later than C<gettimeofday()> and C<Time::HiRes::time()>.
599
600Adjusting the system clock (either manually or by services like ntp)
601may cause problems, especially for long running programs that assume
602a monotonously increasing time (note that all platforms do not adjust
603time as gracefully as UNIX ntp does). For example in Win32 (and derived
604platforms like Cygwin and MinGW) the Time::HiRes::time() may temporarily
605drift off from the system clock (and the original time()) by up to 0.5
606seconds. Time::HiRes will notice this eventually and recalibrate.
ced84e60 607Note that since Time::HiRes 1.77 the clock_gettime(CLOCK_MONOTONIC)
1a7d3a53 608might help in this (in case your system supports CLOCK_MONOTONIC).
f03b998d 609
e5620114
RGS
610Some systems have APIs but not implementations: for example QNX and Haiku
611have the interval timer APIs but not the functionality.
612
c4a535af
SH
613In pre-Sierra macOS (pre-10.12, OS X) clock_getres(), clock_gettime()
614and clock_nanosleep() are emulated using the Mach timers; as a side
615effect of being emulated the CLOCK_REALTIME and CLOCK_MONOTONIC are
616the same timer.
617
618gnukfreebsd seems to have non-functional futimens() and utimensat()
619(at least as of 10.1): therefore the hires utime() does not work.
3b614a59 620
26e22fd9
RGS
621=head1 SEE ALSO
622
ced84e60
SP
623Perl modules L<BSD::Resource>, L<Time::TAI64>.
624
bfe77af1
SP
625Your system documentation for C<clock>, C<clock_gettime>,
626C<clock_getres>, C<clock_nanosleep>, C<clock_settime>, C<getitimer>,
627C<gettimeofday>, C<setitimer>, C<sleep>, C<stat>, C<ualarm>.
26e22fd9 628
dcf686c9
JH
629=head1 AUTHORS
630
631D. Wegscheid <wegscd@whirlpool.com>
632R. Schertler <roderick@argon.org>
633J. Hietaniemi <jhi@iki.fi>
634G. Aas <gisle@aas.no>
635
3f2ee006 636=head1 COPYRIGHT AND LICENSE
dcf686c9 637
3f2ee006 638Copyright (c) 1996-2002 Douglas E. Wegscheid. All rights reserved.
dcf686c9 639
bf8300de
RGS
640Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007, 2008 Jarkko Hietaniemi.
641All rights reserved.
dcf686c9 642
0f0eae2c 643Copyright (C) 2011, 2012, 2013 Andrew Main (Zefram) <zefram@fysh.org>
91a2e9f6 644
3f2ee006
HS
645This program is free software; you can redistribute it and/or modify
646it under the same terms as Perl itself.
dcf686c9
JH
647
648=cut