This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
42f0fc24bc85a56ba5e7f45d6811cc119780b7fa
[perl5.git] / dist / Time-HiRes / HiRes.xs
1 /*
2  * 
3  * Copyright (c) 1996-2002 Douglas E. Wegscheid.  All rights reserved.
4  * 
5  * Copyright (c) 2002-2010 Jarkko Hietaniemi.
6  * All rights reserved.
7  *
8  * Copyright (C) 2011, 2012, 2013 Andrew Main (Zefram) <zefram@fysh.org>
9  * 
10  * This program is free software; you can redistribute it and/or modify
11  * it under the same terms as Perl itself.
12  */
13
14 #ifdef __cplusplus
15 extern "C" {
16 #endif
17 #define PERL_NO_GET_CONTEXT
18 #include "EXTERN.h"
19 #include "perl.h"
20 #include "XSUB.h"
21 #include "ppport.h"
22 #if defined(__CYGWIN__) && defined(HAS_W32API_WINDOWS_H)
23 # include <w32api/windows.h>
24 # define CYGWIN_WITH_W32API
25 #endif
26 #ifdef WIN32
27 # include <time.h>
28 #else
29 # include <sys/time.h>
30 #endif
31 #ifdef HAS_SELECT
32 # ifdef I_SYS_SELECT
33 #  include <sys/select.h>
34 # endif
35 #endif
36 #if defined(TIME_HIRES_CLOCK_GETTIME_SYSCALL) || defined(TIME_HIRES_CLOCK_GETRES_SYSCALL)
37 #include <syscall.h>
38 #endif
39 #ifdef __cplusplus
40 }
41 #endif
42
43 #define PERL_VERSION_DECIMAL(r,v,s) (r*1000000 + v*1000 + s)
44 #define PERL_DECIMAL_VERSION \
45         PERL_VERSION_DECIMAL(PERL_REVISION,PERL_VERSION,PERL_SUBVERSION)
46 #define PERL_VERSION_GE(r,v,s) \
47         (PERL_DECIMAL_VERSION >= PERL_VERSION_DECIMAL(r,v,s))
48
49 /* At least ppport.h 3.13 gets this wrong: one really cannot
50  * have NVgf as anything else than "g" under Perl 5.6.x. */
51 #if PERL_REVISION == 5 && PERL_VERSION == 6
52 # undef NVgf
53 # define NVgf "g"
54 #endif
55
56 #if PERL_VERSION_GE(5,7,3) && !PERL_VERSION_GE(5,10,1)
57 # undef SAVEOP
58 # define SAVEOP() SAVEVPTR(PL_op)
59 #endif
60
61 #define IV_1E6 1000000
62 #define IV_1E7 10000000
63 #define IV_1E9 1000000000
64
65 #define NV_1E6 1000000.0
66 #define NV_1E7 10000000.0
67 #define NV_1E9 1000000000.0
68
69 #ifndef PerlProc_pause
70 #   define PerlProc_pause() Pause()
71 #endif
72
73 #ifdef HAS_PAUSE
74 #   define Pause   pause
75 #else
76 #   undef Pause /* In case perl.h did it already. */
77 #   define Pause() sleep(~0) /* Zzz for a long time. */
78 #endif
79
80 /* Though the cpp define ITIMER_VIRTUAL is available the functionality
81  * is not supported in Cygwin as of August 2004, ditto for Win32.
82  * Neither are ITIMER_PROF or ITIMER_REALPROF implemented.  --jhi
83  */
84 #if defined(__CYGWIN__) || defined(WIN32)
85 #   undef ITIMER_VIRTUAL
86 #   undef ITIMER_PROF
87 #   undef ITIMER_REALPROF
88 #endif
89
90 #if defined(TIME_HIRES_CLOCK_GETTIME) && defined(_STRUCT_ITIMERSPEC)
91
92 /* HP-UX has CLOCK_XXX values but as enums, not as defines.
93  * The only way to detect these would be to test compile for each. */
94 # ifdef __hpux
95 /* However, it seems that at least in HP-UX 11.31 ia64 there *are*
96  * defines for these, so let's try detecting them. */
97 #  ifndef CLOCK_REALTIME
98 #    define CLOCK_REALTIME CLOCK_REALTIME
99 #    define CLOCK_VIRTUAL  CLOCK_VIRTUAL
100 #    define CLOCK_PROFILE  CLOCK_PROFILE
101 #  endif
102 # endif /* # ifdef __hpux */
103
104 #endif /* #if defined(TIME_HIRES_CLOCK_GETTIME) && defined(_STRUCT_ITIMERSPEC) */
105
106 #if defined(WIN32) || defined(CYGWIN_WITH_W32API)
107
108 #ifndef HAS_GETTIMEOFDAY
109 #   define HAS_GETTIMEOFDAY
110 #endif
111
112 /* shows up in winsock.h?
113 struct timeval {
114  long tv_sec;
115  long tv_usec;
116 }
117 */
118
119 typedef union {
120     unsigned __int64    ft_i64;
121     FILETIME            ft_val;
122 } FT_t;
123
124 #define MY_CXT_KEY "Time::HiRes_" XS_VERSION
125
126 typedef struct {
127     unsigned long run_count;
128     unsigned __int64 base_ticks;
129     unsigned __int64 tick_frequency;
130     FT_t base_systime_as_filetime;
131     unsigned __int64 reset_time;
132 } my_cxt_t;
133
134 START_MY_CXT
135
136 /* Number of 100 nanosecond units from 1/1/1601 to 1/1/1970 */
137 #ifdef __GNUC__
138 # define Const64(x) x##LL
139 #else
140 # define Const64(x) x##i64
141 #endif
142 #define EPOCH_BIAS  Const64(116444736000000000)
143
144 #ifdef Const64
145 # ifdef __GNUC__
146 #  define IV_1E6LL  1000000LL /* Needed because of Const64() ##-appends LL (or i64). */
147 #  define IV_1E7LL  10000000LL
148 #  define IV_1E9LL  1000000000LL
149 # else
150 #  define IV_1E6i64 1000000i64
151 #  define IV_1E7i64 10000000i64
152 #  define IV_1E9i64 1000000000i64
153 # endif
154 #endif
155
156 /* NOTE: This does not compute the timezone info (doing so can be expensive,
157  * and appears to be unsupported even by glibc) */
158
159 /* dMY_CXT needs a Perl context and we don't want to call PERL_GET_CONTEXT
160    for performance reasons */
161
162 #undef gettimeofday
163 #define gettimeofday(tp, not_used) _gettimeofday(aTHX_ tp, not_used)
164
165 /* If the performance counter delta drifts more than 0.5 seconds from the
166  * system time then we recalibrate to the system time.  This means we may
167  * move *backwards* in time! */
168 #define MAX_PERF_COUNTER_SKEW Const64(5000000) /* 0.5 seconds */
169
170 /* Reset reading from the performance counter every five minutes.
171  * Many PC clocks just seem to be so bad. */
172 #define MAX_PERF_COUNTER_TICKS Const64(300000000) /* 300 seconds */
173
174 static int
175 _gettimeofday(pTHX_ struct timeval *tp, void *not_used)
176 {
177     dMY_CXT;
178
179     unsigned __int64 ticks;
180     FT_t ft;
181
182     PERL_UNUSED_ARG(not_used);
183     if (MY_CXT.run_count++ == 0 ||
184         MY_CXT.base_systime_as_filetime.ft_i64 > MY_CXT.reset_time) {
185         QueryPerformanceFrequency((LARGE_INTEGER*)&MY_CXT.tick_frequency);
186         QueryPerformanceCounter((LARGE_INTEGER*)&MY_CXT.base_ticks);
187         GetSystemTimeAsFileTime(&MY_CXT.base_systime_as_filetime.ft_val);
188         ft.ft_i64 = MY_CXT.base_systime_as_filetime.ft_i64;
189         MY_CXT.reset_time = ft.ft_i64 + MAX_PERF_COUNTER_TICKS;
190     }
191     else {
192         __int64 diff;
193         QueryPerformanceCounter((LARGE_INTEGER*)&ticks);
194         ticks -= MY_CXT.base_ticks;
195         ft.ft_i64 = MY_CXT.base_systime_as_filetime.ft_i64
196                     + Const64(IV_1E7) * (ticks / MY_CXT.tick_frequency)
197                     +(Const64(IV_1E7) * (ticks % MY_CXT.tick_frequency)) / MY_CXT.tick_frequency;
198         diff = ft.ft_i64 - MY_CXT.base_systime_as_filetime.ft_i64;
199         if (diff < -MAX_PERF_COUNTER_SKEW || diff > MAX_PERF_COUNTER_SKEW) {
200             MY_CXT.base_ticks += ticks;
201             GetSystemTimeAsFileTime(&MY_CXT.base_systime_as_filetime.ft_val);
202             ft.ft_i64 = MY_CXT.base_systime_as_filetime.ft_i64;
203         }
204     }
205
206     /* seconds since epoch */
207     tp->tv_sec = (long)((ft.ft_i64 - EPOCH_BIAS) / Const64(IV_1E7));
208
209     /* microseconds remaining */
210     tp->tv_usec = (long)((ft.ft_i64 / Const64(10)) % Const64(IV_1E6));
211
212     return 0;
213 }
214 #endif
215
216 #if defined(WIN32) && !defined(ATLEASTFIVEOHOHFIVE)
217 static unsigned int
218 sleep(unsigned int t)
219 {
220     Sleep(t*1000);
221     return 0;
222 }
223 #endif
224
225 #if !defined(HAS_GETTIMEOFDAY) && defined(VMS)
226 #define HAS_GETTIMEOFDAY
227
228 #include <lnmdef.h>
229 #include <time.h> /* gettimeofday */
230 #include <stdlib.h> /* qdiv */
231 #include <starlet.h> /* sys$gettim */
232 #include <descrip.h>
233 #ifdef __VAX
234 #include <lib$routines.h> /* lib$ediv() */
235 #endif
236
237 /*
238         VMS binary time is expressed in 100 nano-seconds since
239         system base time which is 17-NOV-1858 00:00:00.00
240 */
241
242 #define DIV_100NS_TO_SECS  10000000L
243 #define DIV_100NS_TO_USECS 10L
244
245 /* 
246         gettimeofday is supposed to return times since the epoch
247         so need to determine this in terms of VMS base time
248 */
249 static $DESCRIPTOR(dscepoch,"01-JAN-1970 00:00:00.00");
250
251 #ifdef __VAX
252 static long base_adjust[2]={0L,0L};
253 #else
254 static __int64 base_adjust=0;
255 #endif
256
257 /* 
258
259    If we don't have gettimeofday, then likely we are on a VMS machine that
260    operates on local time rather than UTC...so we have to zone-adjust.
261    This code gleefully swiped from VMS.C 
262
263 */
264 /* method used to handle UTC conversions:
265  *   1 == CRTL gmtime();  2 == SYS$TIMEZONE_DIFFERENTIAL;  3 == no correction
266  */
267 static int gmtime_emulation_type;
268 /* number of secs to add to UTC POSIX-style time to get local time */
269 static long int utc_offset_secs;
270 static struct dsc$descriptor_s fildevdsc = 
271   { 12, DSC$K_DTYPE_T, DSC$K_CLASS_S, "LNM$FILE_DEV" };
272 static struct dsc$descriptor_s *fildev[] = { &fildevdsc, NULL };
273
274 static time_t toutc_dst(time_t loc) {
275   struct tm *rsltmp;
276
277   if ((rsltmp = localtime(&loc)) == NULL) return -1;
278   loc -= utc_offset_secs;
279   if (rsltmp->tm_isdst) loc -= 3600;
280   return loc;
281 }
282
283 static time_t toloc_dst(time_t utc) {
284   struct tm *rsltmp;
285
286   utc += utc_offset_secs;
287   if ((rsltmp = localtime(&utc)) == NULL) return -1;
288   if (rsltmp->tm_isdst) utc += 3600;
289   return utc;
290 }
291
292 #define _toutc(secs)  ((secs) == (time_t) -1 ? (time_t) -1 : \
293        ((gmtime_emulation_type || timezone_setup()), \
294        (gmtime_emulation_type == 1 ? toutc_dst(secs) : \
295        ((secs) - utc_offset_secs))))
296
297 #define _toloc(secs)  ((secs) == (time_t) -1 ? (time_t) -1 : \
298        ((gmtime_emulation_type || timezone_setup()), \
299        (gmtime_emulation_type == 1 ? toloc_dst(secs) : \
300        ((secs) + utc_offset_secs))))
301
302 static int
303 timezone_setup(void) 
304 {
305   struct tm *tm_p;
306
307   if (gmtime_emulation_type == 0) {
308     int dstnow;
309     time_t base = 15 * 86400; /* 15jan71; to avoid month/year ends between    */
310                               /* results of calls to gmtime() and localtime() */
311                               /* for same &base */
312
313     gmtime_emulation_type++;
314     if ((tm_p = gmtime(&base)) == NULL) { /* CRTL gmtime() is a fake */
315       char off[LNM$C_NAMLENGTH+1];;
316
317       gmtime_emulation_type++;
318       if (!Perl_vmstrnenv("SYS$TIMEZONE_DIFFERENTIAL",off,0,fildev,0)) {
319         gmtime_emulation_type++;
320         utc_offset_secs = 0;
321         Perl_warn(aTHX_ "no UTC offset information; assuming local time is UTC");
322       }
323       else { utc_offset_secs = atol(off); }
324     }
325     else { /* We've got a working gmtime() */
326       struct tm gmt, local;
327
328       gmt = *tm_p;
329       tm_p = localtime(&base);
330       local = *tm_p;
331       utc_offset_secs  = (local.tm_mday - gmt.tm_mday) * 86400;
332       utc_offset_secs += (local.tm_hour - gmt.tm_hour) * 3600;
333       utc_offset_secs += (local.tm_min  - gmt.tm_min)  * 60;
334       utc_offset_secs += (local.tm_sec  - gmt.tm_sec);
335     }
336   }
337   return 1;
338 }
339
340
341 int
342 gettimeofday (struct timeval *tp, void *tpz)
343 {
344  long ret;
345 #ifdef __VAX
346  long quad[2];
347  long quad1[2];
348  long div_100ns_to_secs;
349  long div_100ns_to_usecs;
350  long quo,rem;
351  long quo1,rem1;
352 #else
353  __int64 quad;
354  __qdiv_t ans1,ans2;
355 #endif
356 /*
357         In case of error, tv_usec = 0 and tv_sec = VMS condition code.
358         The return from function is also set to -1.
359         This is not exactly as per the manual page.
360 */
361
362  tp->tv_usec = 0;
363
364 #ifdef __VAX
365  if (base_adjust[0]==0 && base_adjust[1]==0) {
366 #else
367  if (base_adjust==0) { /* Need to determine epoch adjustment */
368 #endif
369         ret=sys$bintim(&dscepoch,&base_adjust);
370         if (1 != (ret &&1)) {
371                 tp->tv_sec = ret;
372                 return -1;
373         }
374  }
375
376  ret=sys$gettim(&quad); /* Get VMS system time */
377  if ((1 && ret) == 1) {
378 #ifdef __VAX
379         quad[0] -= base_adjust[0]; /* convert to epoch offset */
380         quad[1] -= base_adjust[1]; /* convert 2nd half of quadword */
381         div_100ns_to_secs = DIV_100NS_TO_SECS;
382         div_100ns_to_usecs = DIV_100NS_TO_USECS;
383         lib$ediv(&div_100ns_to_secs,&quad,&quo,&rem);
384         quad1[0] = rem;
385         quad1[1] = 0L;
386         lib$ediv(&div_100ns_to_usecs,&quad1,&quo1,&rem1);
387         tp->tv_sec = quo; /* Whole seconds */
388         tp->tv_usec = quo1; /* Micro-seconds */
389 #else
390         quad -= base_adjust; /* convert to epoch offset */
391         ans1=qdiv(quad,DIV_100NS_TO_SECS);
392         ans2=qdiv(ans1.rem,DIV_100NS_TO_USECS);
393         tp->tv_sec = ans1.quot; /* Whole seconds */
394         tp->tv_usec = ans2.quot; /* Micro-seconds */
395 #endif
396  } else {
397         tp->tv_sec = ret;
398         return -1;
399  }
400 # ifdef VMSISH_TIME
401 # ifdef RTL_USES_UTC
402   if (VMSISH_TIME) tp->tv_sec = _toloc(tp->tv_sec);
403 # else
404   if (!VMSISH_TIME) tp->tv_sec = _toutc(tp->tv_sec);
405 # endif
406 # endif
407  return 0;
408 }
409 #endif
410
411
412  /* Do not use H A S _ N A N O S L E E P
413   * so that Perl Configure doesn't scan for it (and pull in -lrt and
414   * the like which are not usually good ideas for the default Perl).
415   * (We are part of the core perl now.)
416   * The TIME_HIRES_NANOSLEEP is set by Makefile.PL. */
417 #if !defined(HAS_USLEEP) && defined(TIME_HIRES_NANOSLEEP)
418 #define HAS_USLEEP
419 #define usleep hrt_usleep  /* could conflict with ncurses for static build */
420
421 static void
422 hrt_usleep(unsigned long usec) /* This is used to emulate usleep. */
423 {
424     struct timespec res;
425     res.tv_sec = usec / IV_1E6;
426     res.tv_nsec = ( usec - res.tv_sec * IV_1E6 ) * 1000;
427     nanosleep(&res, NULL);
428 }
429
430 #endif /* #if !defined(HAS_USLEEP) && defined(TIME_HIRES_NANOSLEEP) */
431
432 #if !defined(HAS_USLEEP) && defined(HAS_SELECT)
433 #ifndef SELECT_IS_BROKEN
434 #define HAS_USLEEP
435 #define usleep hrt_usleep  /* could conflict with ncurses for static build */
436
437 static void
438 hrt_usleep(unsigned long usec)
439 {
440     struct timeval tv;
441     tv.tv_sec = 0;
442     tv.tv_usec = usec;
443     select(0, (Select_fd_set_t)NULL, (Select_fd_set_t)NULL,
444                 (Select_fd_set_t)NULL, &tv);
445 }
446 #endif
447 #endif /* #if !defined(HAS_USLEEP) && defined(HAS_SELECT) */
448
449 #if !defined(HAS_USLEEP) && defined(WIN32)
450 #define HAS_USLEEP
451 #define usleep hrt_usleep  /* could conflict with ncurses for static build */
452
453 static void
454 hrt_usleep(unsigned long usec)
455 {
456     long msec;
457     msec = usec / 1000;
458     Sleep (msec);
459 }
460 #endif /* #if !defined(HAS_USLEEP) && defined(WIN32) */
461
462 #if !defined(HAS_USLEEP) && defined(HAS_POLL)
463 #define HAS_USLEEP
464 #define usleep hrt_usleep  /* could conflict with ncurses for static build */
465
466 static void
467 hrt_usleep(unsigned long usec)
468 {
469     int msec = usec / 1000;
470     poll(0, 0, msec);
471 }
472
473 #endif /* #if !defined(HAS_USLEEP) && defined(HAS_POLL) */
474
475 #if defined(HAS_SETITIMER) && defined(ITIMER_REAL)
476
477 static int
478 hrt_ualarm_itimero(struct itimerval *oitv, int usec, int uinterval)
479 {
480    struct itimerval itv;
481    itv.it_value.tv_sec = usec / IV_1E6;
482    itv.it_value.tv_usec = usec % IV_1E6;
483    itv.it_interval.tv_sec = uinterval / IV_1E6;
484    itv.it_interval.tv_usec = uinterval % IV_1E6;
485    return setitimer(ITIMER_REAL, &itv, oitv);
486 }
487
488 static int
489 hrt_ualarm_itimer(int usec, int uinterval)
490 {
491   return hrt_ualarm_itimero(NULL, usec, uinterval);
492 }
493
494 #endif /* #if !defined(HAS_UALARM) && defined(HAS_SETITIMER) */
495
496 #if !defined(HAS_UALARM) && defined(HAS_SETITIMER)
497 #define HAS_UALARM
498 #define ualarm hrt_ualarm_itimer  /* could conflict with ncurses for static build */
499 #endif
500
501 #if !defined(HAS_UALARM) && defined(VMS)
502 #define HAS_UALARM
503 #define ualarm vms_ualarm 
504
505 #include <lib$routines.h>
506 #include <ssdef.h>
507 #include <starlet.h>
508 #include <descrip.h>
509 #include <signal.h>
510 #include <jpidef.h>
511 #include <psldef.h>
512
513 #define VMSERR(s)   (!((s)&1))
514
515 static void
516 us_to_VMS(useconds_t mseconds, unsigned long v[])
517 {
518     int iss;
519     unsigned long qq[2];
520
521     qq[0] = mseconds;
522     qq[1] = 0;
523     v[0] = v[1] = 0;
524
525     iss = lib$addx(qq,qq,qq);
526     if (VMSERR(iss)) lib$signal(iss);
527     iss = lib$subx(v,qq,v);
528     if (VMSERR(iss)) lib$signal(iss);
529     iss = lib$addx(qq,qq,qq);
530     if (VMSERR(iss)) lib$signal(iss);
531     iss = lib$subx(v,qq,v);
532     if (VMSERR(iss)) lib$signal(iss);
533     iss = lib$subx(v,qq,v);
534     if (VMSERR(iss)) lib$signal(iss);
535 }
536
537 static int
538 VMS_to_us(unsigned long v[])
539 {
540     int iss;
541     unsigned long div=10,quot, rem;
542
543     iss = lib$ediv(&div,v,&quot,&rem);
544     if (VMSERR(iss)) lib$signal(iss);
545
546     return quot;
547 }
548
549 typedef unsigned short word;
550 typedef struct _ualarm {
551     int function;
552     int repeat;
553     unsigned long delay[2];
554     unsigned long interval[2];
555     unsigned long remain[2];
556 } Alarm;
557
558
559 static int alarm_ef;
560 static Alarm *a0, alarm_base;
561 #define UAL_NULL   0
562 #define UAL_SET    1
563 #define UAL_CLEAR  2
564 #define UAL_ACTIVE 4
565 static void ualarm_AST(Alarm *a);
566
567 static int 
568 vms_ualarm(int mseconds, int interval)
569 {
570     Alarm *a, abase;
571     struct item_list3 {
572         word length;
573         word code;
574         void *bufaddr;
575         void *retlenaddr;
576     } ;
577     static struct item_list3 itmlst[2];
578     static int first = 1;
579     unsigned long asten;
580     int iss, enabled;
581
582     if (first) {
583         first = 0;
584         itmlst[0].code       = JPI$_ASTEN;
585         itmlst[0].length     = sizeof(asten);
586         itmlst[0].retlenaddr = NULL;
587         itmlst[1].code       = 0;
588         itmlst[1].length     = 0;
589         itmlst[1].bufaddr    = NULL;
590         itmlst[1].retlenaddr = NULL;
591
592         iss = lib$get_ef(&alarm_ef);
593         if (VMSERR(iss)) lib$signal(iss);
594
595         a0 = &alarm_base;
596         a0->function = UAL_NULL;
597     }
598     itmlst[0].bufaddr    = &asten;
599     
600     iss = sys$getjpiw(0,0,0,itmlst,0,0,0);
601     if (VMSERR(iss)) lib$signal(iss);
602     if (!(asten&0x08)) return -1;
603
604     a = &abase;
605     if (mseconds) {
606         a->function = UAL_SET;
607     } else {
608         a->function = UAL_CLEAR;
609     }
610
611     us_to_VMS(mseconds, a->delay);
612     if (interval) {
613         us_to_VMS(interval, a->interval);
614         a->repeat = 1;
615     } else 
616         a->repeat = 0;
617
618     iss = sys$clref(alarm_ef);
619     if (VMSERR(iss)) lib$signal(iss);
620
621     iss = sys$dclast(ualarm_AST,a,0);
622     if (VMSERR(iss)) lib$signal(iss);
623
624     iss = sys$waitfr(alarm_ef);
625     if (VMSERR(iss)) lib$signal(iss);
626
627     if (a->function == UAL_ACTIVE) 
628         return VMS_to_us(a->remain);
629     else
630         return 0;
631 }
632
633
634
635 static void
636 ualarm_AST(Alarm *a)
637 {
638     int iss;
639     unsigned long now[2];
640
641     iss = sys$gettim(now);
642     if (VMSERR(iss)) lib$signal(iss);
643
644     if (a->function == UAL_SET || a->function == UAL_CLEAR) {
645         if (a0->function == UAL_ACTIVE) {
646             iss = sys$cantim(a0,PSL$C_USER);
647             if (VMSERR(iss)) lib$signal(iss);
648
649             iss = lib$subx(a0->remain, now, a->remain);
650             if (VMSERR(iss)) lib$signal(iss);
651
652             if (a->remain[1] & 0x80000000) 
653                 a->remain[0] = a->remain[1] = 0;
654         }
655
656         if (a->function == UAL_SET) {
657             a->function = a0->function;
658             a0->function = UAL_ACTIVE;
659             a0->repeat = a->repeat;
660             if (a0->repeat) {
661                 a0->interval[0] = a->interval[0];
662                 a0->interval[1] = a->interval[1];
663             }
664             a0->delay[0] = a->delay[0];
665             a0->delay[1] = a->delay[1];
666
667             iss = lib$subx(now, a0->delay, a0->remain);
668             if (VMSERR(iss)) lib$signal(iss);
669
670             iss = sys$setimr(0,a0->delay,ualarm_AST,a0);
671             if (VMSERR(iss)) lib$signal(iss);
672         } else {
673             a->function = a0->function;
674             a0->function = UAL_NULL;
675         }
676         iss = sys$setef(alarm_ef);
677         if (VMSERR(iss)) lib$signal(iss);
678     } else if (a->function == UAL_ACTIVE) {
679         if (a->repeat) {
680             iss = lib$subx(now, a->interval, a->remain);
681             if (VMSERR(iss)) lib$signal(iss);
682
683             iss = sys$setimr(0,a->interval,ualarm_AST,a);
684             if (VMSERR(iss)) lib$signal(iss);
685         } else {
686             a->function = UAL_NULL;
687         }
688         iss = sys$wake(0,0);
689         if (VMSERR(iss)) lib$signal(iss);
690         lib$signal(SS$_ASTFLT);
691     } else {
692         lib$signal(SS$_BADPARAM);
693     }
694 }
695
696 #endif /* #if !defined(HAS_UALARM) && defined(VMS) */
697
698 #ifdef HAS_GETTIMEOFDAY
699
700 static int
701 myU2time(pTHX_ UV *ret)
702 {
703   struct timeval Tp;
704   int status;
705   status = gettimeofday (&Tp, NULL);
706   ret[0] = Tp.tv_sec;
707   ret[1] = Tp.tv_usec;
708   return status;
709 }
710
711 static NV
712 myNVtime()
713 {
714 #ifdef WIN32
715   dTHX;
716 #endif
717   struct timeval Tp;
718   int status;
719   status = gettimeofday (&Tp, NULL);
720   return status == 0 ? Tp.tv_sec + (Tp.tv_usec / NV_1E6) : -1.0;
721 }
722
723 #endif /* #ifdef HAS_GETTIMEOFDAY */
724
725 static void
726 hrstatns(UV *atime_nsec, UV *mtime_nsec, UV *ctime_nsec)
727 {
728   dTHX;
729 #if TIME_HIRES_STAT == 1
730   *atime_nsec = PL_statcache.st_atimespec.tv_nsec;
731   *mtime_nsec = PL_statcache.st_mtimespec.tv_nsec;
732   *ctime_nsec = PL_statcache.st_ctimespec.tv_nsec;
733 #elif TIME_HIRES_STAT == 2
734   *atime_nsec = PL_statcache.st_atimensec;
735   *mtime_nsec = PL_statcache.st_mtimensec;
736   *ctime_nsec = PL_statcache.st_ctimensec;
737 #elif TIME_HIRES_STAT == 3
738   *atime_nsec = PL_statcache.st_atime_n;
739   *mtime_nsec = PL_statcache.st_mtime_n;
740   *ctime_nsec = PL_statcache.st_ctime_n;
741 #elif TIME_HIRES_STAT == 4
742   *atime_nsec = PL_statcache.st_atim.tv_nsec;
743   *mtime_nsec = PL_statcache.st_mtim.tv_nsec;
744   *ctime_nsec = PL_statcache.st_ctim.tv_nsec;
745 #elif TIME_HIRES_STAT == 5
746   *atime_nsec = PL_statcache.st_uatime * 1000;
747   *mtime_nsec = PL_statcache.st_umtime * 1000;
748   *ctime_nsec = PL_statcache.st_uctime * 1000;
749 #else /* !TIME_HIRES_STAT */
750   *atime_nsec = 0;
751   *mtime_nsec = 0;
752   *ctime_nsec = 0;
753 #endif /* !TIME_HIRES_STAT */
754 }
755
756 /* Until Apple implements clock_gettime() (ditto clock_getres())
757  * we will emulate it using Mach interfaces. */
758 #if defined(PERL_DARWIN) && !defined(CLOCK_REALTIME)
759
760 #  include <mach/mach_time.h>
761
762 #  define CLOCK_REALTIME  0x01
763 #  define CLOCK_MONOTONIC 0x02
764
765 #  define TIMER_ABSTIME   0x01
766
767 #ifdef USE_ITHREADS
768 STATIC perl_mutex darwin_time_mutex;
769 #endif
770
771 static uint64_t absolute_time_init;
772 static mach_timebase_info_data_t timebase_info;
773 static struct timespec timespec_init;
774
775 static int darwin_time_init() {
776 #ifdef USE_ITHREADS
777   MUTEX_LOCK(&darwin_time_mutex);
778 #endif
779   struct timeval tv;
780   int success = 1;
781   if (absolute_time_init == 0) {
782     /* mach_absolute_time() cannot fail */
783     absolute_time_init = mach_absolute_time();
784     success = mach_timebase_info(&timebase_info) == KERN_SUCCESS;
785     if (success) {
786       success = gettimeofday(&tv, NULL) == 0;
787       if (success) {
788         timespec_init.tv_sec  = tv.tv_sec;
789         timespec_init.tv_nsec = tv.tv_usec * 1000;
790       }
791     }
792   }
793 #ifdef USE_ITHREADS
794   MUTEX_UNLOCK(&darwin_time_mutex);
795 #endif
796   return success;
797 }
798
799 static int clock_gettime(int clock_id, struct timespec *ts) {
800   if (darwin_time_init() && timebase_info.denom) {
801     switch (clock_id) {
802       case CLOCK_REALTIME:
803       {
804         uint64_t nanos =
805           ((mach_absolute_time() - absolute_time_init) *
806            (uint64_t)timebase_info.numer) / (uint64_t)timebase_info.denom;
807         ts->tv_sec  = timespec_init.tv_sec  + nanos / IV_1E9;
808         ts->tv_nsec = timespec_init.tv_nsec + nanos % IV_1E9;
809         return 0;
810       }
811
812       case CLOCK_MONOTONIC:
813       {
814         uint64_t nanos =
815           (mach_absolute_time() *
816            (uint64_t)timebase_info.numer) / (uint64_t)timebase_info.denom;
817         ts->tv_sec  = nanos / IV_1E9;
818         ts->tv_nsec = nanos - ts->tv_sec * IV_1E9;
819         return 0;
820       }
821
822       default:
823         break;
824     }
825   }
826
827   SETERRNO(EINVAL, LIB_INVARG);
828   return -1;
829 }
830
831 static int clock_getres(int clock_id, struct timespec *ts) {
832   if (darwin_time_init() && timebase_info.denom) {
833     switch (clock_id) {
834       case CLOCK_REALTIME:
835       case CLOCK_MONOTONIC:
836       ts->tv_sec  = 0;
837       /* In newer kernels both the numer and denom are one,
838        * resulting in conversion factor of one, which is of
839        * course unrealistic. */
840       ts->tv_nsec = timebase_info.numer / timebase_info.denom;
841       return 0;
842     default:
843       break;
844     }
845   }
846
847   SETERRNO(EINVAL, LIB_INVARG);
848   return -1;
849 }
850
851 static int clock_nanosleep(int clock_id, int flags,
852                            const struct timespec *rqtp,
853                            struct timespec *rmtp) {
854   if (darwin_time_init()) {
855     switch (clock_id) {
856     case CLOCK_REALTIME:
857     case CLOCK_MONOTONIC:
858       {
859         uint64_t nanos = rqtp->tv_sec * IV_1E9 + rqtp->tv_nsec;
860         int success;
861         if ((flags & TIMER_ABSTIME)) {
862           uint64_t back =
863             timespec_init.tv_sec * IV_1E9 + timespec_init.tv_nsec;
864           nanos = nanos > back ? nanos - back : 0;
865         }
866         success =
867           mach_wait_until(mach_absolute_time() + nanos) == KERN_SUCCESS;
868
869         /* In the relative sleep, the rmtp should be filled in with
870          * the 'unused' part of the rqtp in case the sleep gets
871          * interrupted by a signal.  But it is unknown how signals
872          * interact with mach_wait_until().  In the absolute sleep,
873          * the rmtp should stay untouched. */
874         rmtp->tv_sec  = 0;
875         rmtp->tv_nsec = 0;
876
877         return success;
878       }
879
880     default:
881       break;
882     }
883   }
884
885   SETERRNO(EINVAL, LIB_INVARG);
886   return -1;
887 }
888
889 #endif /* PERL_DARWIN */
890
891 #include "const-c.inc"
892
893 #if (defined(TIME_HIRES_NANOSLEEP)) || \
894     (defined(TIME_HIRES_CLOCK_NANOSLEEP) && defined(TIMER_ABSTIME))
895
896 static void
897 nanosleep_init(NV nsec,
898                     struct timespec *sleepfor,
899                     struct timespec *unslept) {
900   sleepfor->tv_sec = (Time_t)(nsec / NV_1E9);
901   sleepfor->tv_nsec = (long)(nsec - ((NV)sleepfor->tv_sec) * NV_1E9);
902   unslept->tv_sec = 0;
903   unslept->tv_nsec = 0;
904 }
905
906 static NV
907 nsec_without_unslept(struct timespec *sleepfor,
908                      const struct timespec *unslept) {
909   if (sleepfor->tv_sec >= unslept->tv_sec) {
910     sleepfor->tv_sec -= unslept->tv_sec;
911     if (sleepfor->tv_nsec >= unslept->tv_nsec) {
912       sleepfor->tv_nsec -= unslept->tv_nsec;
913     } else if (sleepfor->tv_sec > 0) {
914       sleepfor->tv_sec--;
915       sleepfor->tv_nsec += IV_1E9;
916       sleepfor->tv_nsec -= unslept->tv_nsec;
917     } else {
918       sleepfor->tv_sec = 0;
919       sleepfor->tv_nsec = 0;
920     }
921   } else {
922     sleepfor->tv_sec = 0;
923     sleepfor->tv_nsec = 0;
924   }
925   return ((NV)sleepfor->tv_sec) * NV_1E9 + ((NV)sleepfor->tv_nsec);
926 }
927
928 #endif
929
930 MODULE = Time::HiRes            PACKAGE = Time::HiRes
931
932 PROTOTYPES: ENABLE
933
934 BOOT:
935 {
936 #ifdef MY_CXT_KEY
937   MY_CXT_INIT;
938 #endif
939 #ifdef ATLEASTFIVEOHOHFIVE
940 #   ifdef HAS_GETTIMEOFDAY
941   {
942     (void) hv_store(PL_modglobal, "Time::NVtime", 12,
943                 newSViv(PTR2IV(myNVtime)), 0);
944     (void) hv_store(PL_modglobal, "Time::U2time", 12,
945                 newSViv(PTR2IV(myU2time)), 0);
946   }
947 #   endif
948 #endif
949 }
950
951 #if defined(USE_ITHREADS) && defined(MY_CXT_KEY)
952
953 void
954 CLONE(...)
955     CODE:
956     MY_CXT_CLONE;
957
958 #endif
959
960 INCLUDE: const-xs.inc
961
962 #if defined(HAS_USLEEP) && defined(HAS_GETTIMEOFDAY)
963
964 NV
965 usleep(useconds)
966         NV useconds
967         PREINIT:
968         struct timeval Ta, Tb;
969         CODE:
970         gettimeofday(&Ta, NULL);
971         if (items > 0) {
972             if (useconds >= NV_1E6) {
973                 IV seconds = (IV) (useconds / NV_1E6);
974                 /* If usleep() has been implemented using setitimer()
975                  * then this contortion is unnecessary-- but usleep()
976                  * may be implemented in some other way, so let's contort. */
977                 if (seconds) {
978                     sleep(seconds);
979                     useconds -= NV_1E6 * seconds;
980                 }
981             } else if (useconds < 0.0)
982                 croak("Time::HiRes::usleep(%"NVgf"): negative time not invented yet", useconds);
983             usleep((U32)useconds);
984         } else
985             PerlProc_pause();
986         gettimeofday(&Tb, NULL);
987 #if 0
988         printf("[%ld %ld] [%ld %ld]\n", Tb.tv_sec, Tb.tv_usec, Ta.tv_sec, Ta.tv_usec);
989 #endif
990         RETVAL = NV_1E6*(Tb.tv_sec-Ta.tv_sec)+(NV)((IV)Tb.tv_usec-(IV)Ta.tv_usec);
991
992         OUTPUT:
993         RETVAL
994
995 #if defined(TIME_HIRES_NANOSLEEP)
996
997 NV
998 nanosleep(nsec)
999         NV nsec
1000         PREINIT:
1001         struct timespec sleepfor, unslept;
1002         CODE:
1003         if (nsec < 0.0)
1004             croak("Time::HiRes::nanosleep(%"NVgf"): negative time not invented yet", nsec);
1005         nanosleep_init(nsec, &sleepfor, &unslept);
1006         if (nanosleep(&sleepfor, &unslept) == 0) {
1007             RETVAL = nsec;
1008         } else {
1009             RETVAL = nsec_without_unslept(&sleepfor, &unslept);
1010         }
1011     OUTPUT:
1012         RETVAL
1013
1014 #else  /* #if defined(TIME_HIRES_NANOSLEEP) */
1015
1016 NV
1017 nanosleep(nsec)
1018         NV nsec
1019     CODE:
1020         PERL_UNUSED_ARG(nsec);
1021         croak("Time::HiRes::nanosleep(): unimplemented in this platform");
1022         RETVAL = 0.0;
1023     OUTPUT:
1024         RETVAL
1025
1026 #endif /* #if defined(TIME_HIRES_NANOSLEEP) */
1027
1028 NV
1029 sleep(...)
1030         PREINIT:
1031         struct timeval Ta, Tb;
1032         CODE:
1033         gettimeofday(&Ta, NULL);
1034         if (items > 0) {
1035             NV seconds  = SvNV(ST(0));
1036             if (seconds >= 0.0) {
1037                  UV useconds = (UV)(1E6 * (seconds - (UV)seconds));
1038                  if (seconds >= 1.0)
1039                      sleep((U32)seconds);
1040                  if ((IV)useconds < 0) {
1041 #if defined(__sparc64__) && defined(__GNUC__)
1042                    /* Sparc64 gcc 2.95.3 (e.g. on NetBSD) has a bug
1043                     * where (0.5 - (UV)(0.5)) will under certain
1044                     * circumstances (if the double is cast to UV more
1045                     * than once?) evaluate to -0.5, instead of 0.5. */
1046                    useconds = -(IV)useconds;
1047 #endif /* #if defined(__sparc64__) && defined(__GNUC__) */
1048                    if ((IV)useconds < 0)
1049                      croak("Time::HiRes::sleep(%"NVgf"): internal error: useconds < 0 (unsigned %"UVuf" signed %"IVdf")", seconds, useconds, (IV)useconds);
1050                  }
1051                  usleep(useconds);
1052             } else
1053                 croak("Time::HiRes::sleep(%"NVgf"): negative time not invented yet", seconds);
1054         } else
1055             PerlProc_pause();
1056         gettimeofday(&Tb, NULL);
1057 #if 0
1058         printf("[%ld %ld] [%ld %ld]\n", Tb.tv_sec, Tb.tv_usec, Ta.tv_sec, Ta.tv_usec);
1059 #endif
1060         RETVAL = (NV)(Tb.tv_sec-Ta.tv_sec)+0.000001*(NV)(Tb.tv_usec-Ta.tv_usec);
1061
1062         OUTPUT:
1063         RETVAL
1064
1065 #else  /* #if defined(HAS_USLEEP) && defined(HAS_GETTIMEOFDAY) */
1066
1067 NV
1068 usleep(useconds)
1069         NV useconds
1070     CODE:
1071         PERL_UNUSED_ARG(useconds);
1072         croak("Time::HiRes::usleep(): unimplemented in this platform");
1073         RETVAL = 0.0;
1074     OUTPUT:
1075         RETVAL
1076
1077 #endif /* #if defined(HAS_USLEEP) && defined(HAS_GETTIMEOFDAY) */
1078
1079 #ifdef HAS_UALARM
1080
1081 IV
1082 ualarm(useconds,uinterval=0)
1083         int useconds
1084         int uinterval
1085         CODE:
1086         if (useconds < 0 || uinterval < 0)
1087             croak("Time::HiRes::ualarm(%d, %d): negative time not invented yet", useconds, uinterval);
1088 #if defined(HAS_SETITIMER) && defined(ITIMER_REAL)
1089           {
1090                 struct itimerval itv;
1091                 if (hrt_ualarm_itimero(&itv, useconds, uinterval)) {
1092                   /* To conform to ualarm's interface, we're actually ignoring
1093                      an error here.  */
1094                   RETVAL = 0;
1095                 } else {
1096                   RETVAL = itv.it_value.tv_sec * IV_1E6 + itv.it_value.tv_usec;
1097                 }
1098           }
1099 #else
1100         if (useconds >= IV_1E6 || uinterval >= IV_1E6) 
1101                 croak("Time::HiRes::ualarm(%d, %d): useconds or uinterval equal to or more than %"IVdf, useconds, uinterval, IV_1E6);
1102         RETVAL = ualarm(useconds, uinterval);
1103 #endif
1104
1105         OUTPUT:
1106         RETVAL
1107
1108 NV
1109 alarm(seconds,interval=0)
1110         NV seconds
1111         NV interval
1112         CODE:
1113         if (seconds < 0.0 || interval < 0.0)
1114             croak("Time::HiRes::alarm(%"NVgf", %"NVgf"): negative time not invented yet", seconds, interval);
1115         {
1116           IV iseconds = (IV)seconds;
1117           IV iinterval = (IV)interval;
1118           NV fseconds = seconds - iseconds;
1119           NV finterval = interval - iinterval;
1120           IV useconds, uinterval;
1121           if (fseconds >= 1.0 || finterval >= 1.0)
1122                 croak("Time::HiRes::alarm(%"NVgf", %"NVgf"): seconds or interval too large to split correctly", seconds, interval);
1123           useconds = IV_1E6 * fseconds;
1124           uinterval = IV_1E6 * finterval;
1125 #if defined(HAS_SETITIMER) && defined(ITIMER_REAL)
1126           {
1127                 struct itimerval nitv, oitv;
1128                 nitv.it_value.tv_sec = iseconds;
1129                 nitv.it_value.tv_usec = useconds;
1130                 nitv.it_interval.tv_sec = iinterval;
1131                 nitv.it_interval.tv_usec = uinterval;
1132                 if (setitimer(ITIMER_REAL, &nitv, &oitv)) {
1133                   /* To conform to alarm's interface, we're actually ignoring
1134                      an error here.  */
1135                   RETVAL = 0;
1136                 } else {
1137                   RETVAL = oitv.it_value.tv_sec + ((NV)oitv.it_value.tv_usec) / NV_1E6;
1138                 }
1139           }
1140 #else
1141           if (iseconds || iinterval)
1142                 croak("Time::HiRes::alarm(%"NVgf", %"NVgf"): seconds or interval equal to or more than 1.0 ", seconds, interval);
1143             RETVAL = (NV)ualarm( useconds, uinterval ) / NV_1E6;
1144 #endif
1145         }
1146
1147         OUTPUT:
1148         RETVAL
1149
1150 #else
1151
1152 int
1153 ualarm(useconds,interval=0)
1154         int useconds
1155         int interval
1156     CODE:
1157         PERL_UNUSED_ARG(useconds);
1158         PERL_UNUSED_ARG(interval);
1159         croak("Time::HiRes::ualarm(): unimplemented in this platform");
1160         RETVAL = -1;
1161     OUTPUT:
1162         RETVAL
1163
1164 NV
1165 alarm(seconds,interval=0)
1166         NV seconds
1167         NV interval
1168     CODE:
1169         PERL_UNUSED_ARG(seconds);
1170         PERL_UNUSED_ARG(interval);
1171         croak("Time::HiRes::alarm(): unimplemented in this platform");
1172         RETVAL = 0.0;
1173     OUTPUT:
1174         RETVAL
1175
1176 #endif /* #ifdef HAS_UALARM */
1177
1178 #ifdef HAS_GETTIMEOFDAY
1179 #    ifdef MACOS_TRADITIONAL    /* fix epoch TZ and use unsigned time_t */
1180 void
1181 gettimeofday()
1182         PREINIT:
1183         struct timeval Tp;
1184         struct timezone Tz;
1185         PPCODE:
1186         int status;
1187         status = gettimeofday (&Tp, &Tz);
1188
1189         if (status == 0) {
1190              Tp.tv_sec += Tz.tz_minuteswest * 60;       /* adjust for TZ */
1191              if (GIMME == G_ARRAY) {
1192                  EXTEND(sp, 2);
1193                  /* Mac OS (Classic) has unsigned time_t */
1194                  PUSHs(sv_2mortal(newSVuv(Tp.tv_sec)));
1195                  PUSHs(sv_2mortal(newSViv(Tp.tv_usec)));
1196              } else {
1197                  EXTEND(sp, 1);
1198                  PUSHs(sv_2mortal(newSVnv(Tp.tv_sec + (Tp.tv_usec / NV_1E6))));
1199              }
1200         }
1201
1202 NV
1203 time()
1204         PREINIT:
1205         struct timeval Tp;
1206         struct timezone Tz;
1207         CODE:
1208         int status;
1209         status = gettimeofday (&Tp, &Tz);
1210         if (status == 0) {
1211             Tp.tv_sec += Tz.tz_minuteswest * 60;        /* adjust for TZ */
1212             RETVAL = Tp.tv_sec + (Tp.tv_usec / NV_1E6);
1213         } else {
1214             RETVAL = -1.0;
1215         }
1216         OUTPUT:
1217         RETVAL
1218
1219 #    else       /* MACOS_TRADITIONAL */
1220 void
1221 gettimeofday()
1222         PREINIT:
1223         struct timeval Tp;
1224         PPCODE:
1225         int status;
1226         status = gettimeofday (&Tp, NULL);
1227         if (status == 0) {
1228              if (GIMME == G_ARRAY) {
1229                  EXTEND(sp, 2);
1230                  PUSHs(sv_2mortal(newSViv(Tp.tv_sec)));
1231                  PUSHs(sv_2mortal(newSViv(Tp.tv_usec)));
1232              } else {
1233                  EXTEND(sp, 1);
1234                  PUSHs(sv_2mortal(newSVnv(Tp.tv_sec + (Tp.tv_usec / NV_1E6))));
1235              }
1236         }
1237
1238 NV
1239 time()
1240         PREINIT:
1241         struct timeval Tp;
1242         CODE:
1243         int status;
1244         status = gettimeofday (&Tp, NULL);
1245         if (status == 0) {
1246             RETVAL = Tp.tv_sec + (Tp.tv_usec / NV_1E6);
1247         } else {
1248             RETVAL = -1.0;
1249         }
1250         OUTPUT:
1251         RETVAL
1252
1253 #    endif      /* MACOS_TRADITIONAL */
1254 #endif /* #ifdef HAS_GETTIMEOFDAY */
1255
1256 #if defined(HAS_GETITIMER) && defined(HAS_SETITIMER)
1257
1258 #define TV2NV(tv) ((NV)((tv).tv_sec) + 0.000001 * (NV)((tv).tv_usec))
1259
1260 void
1261 setitimer(which, seconds, interval = 0)
1262         int which
1263         NV seconds
1264         NV interval
1265     PREINIT:
1266         struct itimerval newit;
1267         struct itimerval oldit;
1268     PPCODE:
1269         if (seconds < 0.0 || interval < 0.0)
1270             croak("Time::HiRes::setitimer(%"IVdf", %"NVgf", %"NVgf"): negative time not invented yet", (IV)which, seconds, interval);
1271         newit.it_value.tv_sec  = (IV)seconds;
1272         newit.it_value.tv_usec =
1273           (IV)((seconds  - (NV)newit.it_value.tv_sec)    * NV_1E6);
1274         newit.it_interval.tv_sec  = (IV)interval;
1275         newit.it_interval.tv_usec =
1276           (IV)((interval - (NV)newit.it_interval.tv_sec) * NV_1E6);
1277         /* on some platforms the 1st arg to setitimer is an enum, which
1278          * causes -Wc++-compat to complain about passing an int instead
1279          */
1280 #ifdef GCC_DIAG_IGNORE
1281         GCC_DIAG_IGNORE(-Wc++-compat);
1282 #endif
1283         if (setitimer(which, &newit, &oldit) == 0) {
1284           EXTEND(sp, 1);
1285           PUSHs(sv_2mortal(newSVnv(TV2NV(oldit.it_value))));
1286           if (GIMME == G_ARRAY) {
1287             EXTEND(sp, 1);
1288             PUSHs(sv_2mortal(newSVnv(TV2NV(oldit.it_interval))));
1289           }
1290         }
1291 #ifdef GCC_DIAG_RESTORE
1292         GCC_DIAG_RESTORE;
1293 #endif
1294
1295 void
1296 getitimer(which)
1297         int which
1298     PREINIT:
1299         struct itimerval nowit;
1300     PPCODE:
1301         /* on some platforms the 1st arg to getitimer is an enum, which
1302          * causes -Wc++-compat to complain about passing an int instead
1303          */
1304 #ifdef GCC_DIAG_IGNORE
1305         GCC_DIAG_IGNORE(-Wc++-compat);
1306 #endif
1307         if (getitimer(which, &nowit) == 0) {
1308           EXTEND(sp, 1);
1309           PUSHs(sv_2mortal(newSVnv(TV2NV(nowit.it_value))));
1310           if (GIMME == G_ARRAY) {
1311             EXTEND(sp, 1);
1312             PUSHs(sv_2mortal(newSVnv(TV2NV(nowit.it_interval))));
1313           }
1314         }
1315 #ifdef GCC_DIAG_RESTORE
1316         GCC_DIAG_RESTORE;
1317 #endif
1318
1319 #endif /* #if defined(HAS_GETITIMER) && defined(HAS_SETITIMER) */
1320
1321 #if defined(TIME_HIRES_CLOCK_GETTIME)
1322
1323 NV
1324 clock_gettime(clock_id = CLOCK_REALTIME)
1325         int clock_id
1326     PREINIT:
1327         struct timespec ts;
1328         int status = -1;
1329     CODE:
1330 #ifdef TIME_HIRES_CLOCK_GETTIME_SYSCALL
1331         status = syscall(SYS_clock_gettime, clock_id, &ts);
1332 #else
1333         status = clock_gettime(clock_id, &ts);
1334 #endif
1335         RETVAL = status == 0 ? ts.tv_sec + (NV) ts.tv_nsec / NV_1E9 : -1;
1336
1337     OUTPUT:
1338         RETVAL
1339
1340 #else  /* if defined(TIME_HIRES_CLOCK_GETTIME) */
1341
1342 NV
1343 clock_gettime(clock_id = 0)
1344         int clock_id
1345     CODE:
1346         PERL_UNUSED_ARG(clock_id);
1347         croak("Time::HiRes::clock_gettime(): unimplemented in this platform");
1348         RETVAL = 0.0;
1349     OUTPUT:
1350         RETVAL
1351
1352 #endif /*  #if defined(TIME_HIRES_CLOCK_GETTIME) */
1353
1354 #if defined(TIME_HIRES_CLOCK_GETRES)
1355
1356 NV
1357 clock_getres(clock_id = CLOCK_REALTIME)
1358         int clock_id
1359     PREINIT:
1360         int status = -1;
1361         struct timespec ts;
1362     CODE:
1363 #ifdef TIME_HIRES_CLOCK_GETRES_SYSCALL
1364         status = syscall(SYS_clock_getres, clock_id, &ts);
1365 #else
1366         status = clock_getres(clock_id, &ts);
1367 #endif
1368         RETVAL = status == 0 ? ts.tv_sec + (NV) ts.tv_nsec / NV_1E9 : -1;
1369
1370     OUTPUT:
1371         RETVAL
1372
1373 #else  /* if defined(TIME_HIRES_CLOCK_GETRES) */
1374
1375 NV
1376 clock_getres(clock_id = 0)
1377         int clock_id
1378     CODE:
1379         PERL_UNUSED_ARG(clock_id);
1380         croak("Time::HiRes::clock_getres(): unimplemented in this platform");
1381         RETVAL = 0.0;
1382     OUTPUT:
1383         RETVAL
1384
1385 #endif /*  #if defined(TIME_HIRES_CLOCK_GETRES) */
1386
1387 #if defined(TIME_HIRES_CLOCK_NANOSLEEP) && defined(TIMER_ABSTIME)
1388
1389 NV
1390 clock_nanosleep(clock_id, nsec, flags = 0)
1391         int clock_id
1392         NV  nsec
1393         int flags
1394     PREINIT:
1395         struct timespec sleepfor, unslept;
1396     CODE:
1397         if (nsec < 0.0)
1398             croak("Time::HiRes::clock_nanosleep(..., %"NVgf"): negative time not invented yet", nsec);
1399         nanosleep_init(nsec, &sleepfor, &unslept);
1400         if (clock_nanosleep(clock_id, flags, &sleepfor, &unslept) == 0) {
1401             RETVAL = nsec;
1402         } else {
1403             RETVAL = nsec_without_unslept(&sleepfor, &unslept);
1404         }
1405     OUTPUT:
1406         RETVAL
1407
1408 #else  /* if defined(TIME_HIRES_CLOCK_NANOSLEEP) && defined(TIMER_ABSTIME) */
1409
1410 NV
1411 clock_nanosleep(clock_id, nsec, flags = 0)
1412         int clock_id
1413         NV  nsec
1414         int flags
1415     CODE:
1416         PERL_UNUSED_ARG(clock_id);
1417         PERL_UNUSED_ARG(nsec);
1418         PERL_UNUSED_ARG(flags);
1419         croak("Time::HiRes::clock_nanosleep(): unimplemented in this platform");
1420         RETVAL = 0.0;
1421     OUTPUT:
1422         RETVAL
1423
1424 #endif /*  #if defined(TIME_HIRES_CLOCK_NANOSLEEP) && defined(TIMER_ABSTIME) */
1425
1426 #if defined(TIME_HIRES_CLOCK) && defined(CLOCKS_PER_SEC)
1427
1428 NV
1429 clock()
1430     PREINIT:
1431         clock_t clocks;
1432     CODE:
1433         clocks = clock();
1434         RETVAL = clocks == (clock_t) -1 ? (clock_t) -1 : (NV)clocks / (NV)CLOCKS_PER_SEC;
1435
1436     OUTPUT:
1437         RETVAL
1438
1439 #else  /* if defined(TIME_HIRES_CLOCK) && defined(CLOCKS_PER_SEC) */
1440
1441 NV
1442 clock()
1443     CODE:
1444         croak("Time::HiRes::clock(): unimplemented in this platform");
1445         RETVAL = 0.0;
1446     OUTPUT:
1447         RETVAL
1448
1449 #endif /*  #if defined(TIME_HIRES_CLOCK) && defined(CLOCKS_PER_SEC) */
1450
1451 void
1452 stat(...)
1453 PROTOTYPE: ;$
1454     PREINIT:
1455         OP fakeop;
1456         int nret;
1457     ALIAS:
1458         Time::HiRes::lstat = 1
1459     PPCODE:
1460         XPUSHs(sv_2mortal(newSVsv(items == 1 ? ST(0) : DEFSV)));
1461         PUTBACK;
1462         ENTER;
1463         PL_laststatval = -1;
1464         SAVEOP();
1465         Zero(&fakeop, 1, OP);
1466         fakeop.op_type = ix ? OP_LSTAT : OP_STAT;
1467         fakeop.op_ppaddr = PL_ppaddr[fakeop.op_type];
1468         fakeop.op_flags = GIMME_V == G_ARRAY ? OPf_WANT_LIST :
1469                 GIMME_V == G_SCALAR ? OPf_WANT_SCALAR : OPf_WANT_VOID;
1470         PL_op = &fakeop;
1471         (void)fakeop.op_ppaddr(aTHX);
1472         SPAGAIN;
1473         LEAVE;
1474         nret = SP+1 - &ST(0);
1475         if (nret == 13) {
1476           UV atime = SvUV(ST( 8));
1477           UV mtime = SvUV(ST( 9));
1478           UV ctime = SvUV(ST(10));
1479           UV atime_nsec;
1480           UV mtime_nsec;
1481           UV ctime_nsec;
1482           hrstatns(&atime_nsec, &mtime_nsec, &ctime_nsec);
1483           if (atime_nsec)
1484             ST( 8) = sv_2mortal(newSVnv(atime + (NV) atime_nsec / NV_1E9));
1485           if (mtime_nsec)
1486             ST( 9) = sv_2mortal(newSVnv(mtime + (NV) mtime_nsec / NV_1E9));
1487           if (ctime_nsec)
1488             ST(10) = sv_2mortal(newSVnv(ctime + (NV) ctime_nsec / NV_1E9));
1489         }
1490         XSRETURN(nret);