4c56464065639e94f8593f49ea11c68a14abb06e
[p5sagit/p5-mst-13.2.git] / ext / Time / HiRes / HiRes.xs
1 /*
2  * 
3  * Copyright (c) 1996-2002 Douglas E. Wegscheid.  All rights reserved.
4  * 
5  * Copyright (c) 2002,2003,2004,2005 Jarkko Hietaniemi.  All rights reserved.
6  * 
7  * This program is free software; you can redistribute it and/or modify
8  * it under the same terms as Perl itself.
9  */
10
11 #ifdef __cplusplus
12 extern "C" {
13 #endif
14 #define PERL_NO_GET_CONTEXT
15 #include "EXTERN.h"
16 #include "perl.h"
17 #include "XSUB.h"
18 #include "ppport.h"
19 #if defined(__CYGWIN__) && defined(HAS_W32API_WINDOWS_H)
20 # include <w32api/windows.h>
21 # define CYGWIN_WITH_W32API
22 #endif
23 #ifdef WIN32
24 # include <time.h>
25 #else
26 # include <sys/time.h>
27 #endif
28 #ifdef HAS_SELECT
29 # ifdef I_SYS_SELECT
30 #  include <sys/select.h>
31 # endif
32 #endif
33 #if defined(TIME_HIRES_CLOCK_GETTIME_SYSCALL) || defined(TIME_HIRES_CLOCK_GETRES_SYSCALL)
34 #include <syscall.h>
35 #endif
36 #ifdef __cplusplus
37 }
38 #endif
39
40 #ifndef PerlProc_pause
41 #   define PerlProc_pause() Pause()
42 #endif
43
44 #ifdef HAS_PAUSE
45 #   define Pause   pause
46 #else
47 #   undef Pause /* In case perl.h did it already. */
48 #   define Pause() sleep(~0) /* Zzz for a long time. */
49 #endif
50
51 /* Though the cpp define ITIMER_VIRTUAL is available the functionality
52  * is not supported in Cygwin as of August 2004, ditto for Win32.
53  * Neither are ITIMER_PROF or ITIMER_REALPROF implemented.  --jhi
54  */
55 #if defined(__CYGWIN__) || defined(WIN32)
56 #   undef ITIMER_VIRTUAL
57 #   undef ITIMER_PROF
58 #   undef ITIMER_REALPROF
59 #endif
60
61 /* 5.004 doesn't define PL_sv_undef */
62 #ifndef ATLEASTFIVEOHOHFIVE
63 # ifndef PL_sv_undef
64 #  define PL_sv_undef sv_undef
65 # endif
66 #endif
67
68 #include "const-c.inc"
69
70 #if defined(WIN32) || defined(CYGWIN_WITH_W32API)
71
72 #ifndef HAS_GETTIMEOFDAY
73 #   define HAS_GETTIMEOFDAY
74 #endif
75
76 /* shows up in winsock.h?
77 struct timeval {
78  long tv_sec;
79  long tv_usec;
80 }
81 */
82
83 typedef union {
84     unsigned __int64    ft_i64;
85     FILETIME            ft_val;
86 } FT_t;
87
88 #define MY_CXT_KEY "Time::HiRes_" XS_VERSION
89
90 typedef struct {
91     unsigned long run_count;
92     unsigned __int64 base_ticks;
93     unsigned __int64 tick_frequency;
94     FT_t base_systime_as_filetime;
95     unsigned __int64 reset_time;
96 } my_cxt_t;
97
98 START_MY_CXT
99
100 /* Number of 100 nanosecond units from 1/1/1601 to 1/1/1970 */
101 #ifdef __GNUC__
102 # define Const64(x) x##LL
103 #else
104 # define Const64(x) x##i64
105 #endif
106 #define EPOCH_BIAS  Const64(116444736000000000)
107
108 /* NOTE: This does not compute the timezone info (doing so can be expensive,
109  * and appears to be unsupported even by glibc) */
110
111 /* dMY_CXT needs a Perl context and we don't want to call PERL_GET_CONTEXT
112    for performance reasons */
113
114 #undef gettimeofday
115 #define gettimeofday(tp, not_used) _gettimeofday(aTHX_ tp, not_used)
116
117 /* If the performance counter delta drifts more than 0.5 seconds from the
118  * system time then we recalibrate to the system time.  This means we may
119  * move *backwards* in time! */
120 #define MAX_PERF_COUNTER_SKEW Const64(5000000) /* 0.5 seconds */
121
122 /* Reset reading from the performance counter every five minutes.
123  * Many PC clocks just seem to be so bad. */
124 #define MAX_PERF_COUNTER_TICKS Const64(300000000) /* 300 seconds */
125
126 static int
127 _gettimeofday(pTHX_ struct timeval *tp, void *not_used)
128 {
129     dMY_CXT;
130
131     unsigned __int64 ticks;
132     FT_t ft;
133
134     if (MY_CXT.run_count++ == 0 ||
135         MY_CXT.base_systime_as_filetime.ft_i64 > MY_CXT.reset_time) {
136         QueryPerformanceFrequency((LARGE_INTEGER*)&MY_CXT.tick_frequency);
137         QueryPerformanceCounter((LARGE_INTEGER*)&MY_CXT.base_ticks);
138         GetSystemTimeAsFileTime(&MY_CXT.base_systime_as_filetime.ft_val);
139         ft.ft_i64 = MY_CXT.base_systime_as_filetime.ft_i64;
140         MY_CXT.reset_time = ft.ft_i64 + MAX_PERF_COUNTER_TICKS;
141     }
142     else {
143         __int64 diff;
144         QueryPerformanceCounter((LARGE_INTEGER*)&ticks);
145         ticks -= MY_CXT.base_ticks;
146         ft.ft_i64 = MY_CXT.base_systime_as_filetime.ft_i64
147                     + Const64(10000000) * (ticks / MY_CXT.tick_frequency)
148                     +(Const64(10000000) * (ticks % MY_CXT.tick_frequency)) / MY_CXT.tick_frequency;
149         diff = ft.ft_i64 - MY_CXT.base_systime_as_filetime.ft_i64;
150         if (diff < -MAX_PERF_COUNTER_SKEW || diff > MAX_PERF_COUNTER_SKEW) {
151             MY_CXT.base_ticks += ticks;
152             GetSystemTimeAsFileTime(&MY_CXT.base_systime_as_filetime.ft_val);
153             ft.ft_i64 = MY_CXT.base_systime_as_filetime.ft_i64;
154         }
155     }
156
157     /* seconds since epoch */
158     tp->tv_sec = (long)((ft.ft_i64 - EPOCH_BIAS) / Const64(10000000));
159
160     /* microseconds remaining */
161     tp->tv_usec = (long)((ft.ft_i64 / Const64(10)) % Const64(1000000));
162
163     return 0;
164 }
165 #endif
166
167 #if defined(WIN32) && !defined(ATLEASTFIVEOHOHFIVE)
168 static unsigned int
169 sleep(unsigned int t)
170 {
171     Sleep(t*1000);
172     return 0;
173 }
174 #endif
175
176 #if !defined(HAS_GETTIMEOFDAY) && defined(VMS)
177 #define HAS_GETTIMEOFDAY
178
179 #include <lnmdef.h>
180 #include <time.h> /* gettimeofday */
181 #include <stdlib.h> /* qdiv */
182 #include <starlet.h> /* sys$gettim */
183 #include <descrip.h>
184 #ifdef __VAX
185 #include <lib$routines.h> /* lib$ediv() */
186 #endif
187
188 /*
189         VMS binary time is expressed in 100 nano-seconds since
190         system base time which is 17-NOV-1858 00:00:00.00
191 */
192
193 #define DIV_100NS_TO_SECS  10000000L
194 #define DIV_100NS_TO_USECS 10L
195
196 /* 
197         gettimeofday is supposed to return times since the epoch
198         so need to determine this in terms of VMS base time
199 */
200 static $DESCRIPTOR(dscepoch,"01-JAN-1970 00:00:00.00");
201
202 #ifdef __VAX
203 static long base_adjust[2]={0L,0L};
204 #else
205 static __int64 base_adjust=0;
206 #endif
207
208 /* 
209
210    If we don't have gettimeofday, then likely we are on a VMS machine that
211    operates on local time rather than UTC...so we have to zone-adjust.
212    This code gleefully swiped from VMS.C 
213
214 */
215 /* method used to handle UTC conversions:
216  *   1 == CRTL gmtime();  2 == SYS$TIMEZONE_DIFFERENTIAL;  3 == no correction
217  */
218 static int gmtime_emulation_type;
219 /* number of secs to add to UTC POSIX-style time to get local time */
220 static long int utc_offset_secs;
221 static struct dsc$descriptor_s fildevdsc = 
222   { 12, DSC$K_DTYPE_T, DSC$K_CLASS_S, "LNM$FILE_DEV" };
223 static struct dsc$descriptor_s *fildev[] = { &fildevdsc, NULL };
224
225 static time_t toutc_dst(time_t loc) {
226   struct tm *rsltmp;
227
228   if ((rsltmp = localtime(&loc)) == NULL) return -1;
229   loc -= utc_offset_secs;
230   if (rsltmp->tm_isdst) loc -= 3600;
231   return loc;
232 }
233
234 static time_t toloc_dst(time_t utc) {
235   struct tm *rsltmp;
236
237   utc += utc_offset_secs;
238   if ((rsltmp = localtime(&utc)) == NULL) return -1;
239   if (rsltmp->tm_isdst) utc += 3600;
240   return utc;
241 }
242
243 #define _toutc(secs)  ((secs) == (time_t) -1 ? (time_t) -1 : \
244        ((gmtime_emulation_type || timezone_setup()), \
245        (gmtime_emulation_type == 1 ? toutc_dst(secs) : \
246        ((secs) - utc_offset_secs))))
247
248 #define _toloc(secs)  ((secs) == (time_t) -1 ? (time_t) -1 : \
249        ((gmtime_emulation_type || timezone_setup()), \
250        (gmtime_emulation_type == 1 ? toloc_dst(secs) : \
251        ((secs) + utc_offset_secs))))
252
253 static int
254 timezone_setup(void) 
255 {
256   struct tm *tm_p;
257
258   if (gmtime_emulation_type == 0) {
259     int dstnow;
260     time_t base = 15 * 86400; /* 15jan71; to avoid month/year ends between    */
261                               /* results of calls to gmtime() and localtime() */
262                               /* for same &base */
263
264     gmtime_emulation_type++;
265     if ((tm_p = gmtime(&base)) == NULL) { /* CRTL gmtime() is a fake */
266       char off[LNM$C_NAMLENGTH+1];;
267
268       gmtime_emulation_type++;
269       if (!Perl_vmstrnenv("SYS$TIMEZONE_DIFFERENTIAL",off,0,fildev,0)) {
270         gmtime_emulation_type++;
271         utc_offset_secs = 0;
272         Perl_warn(aTHX_ "no UTC offset information; assuming local time is UTC");
273       }
274       else { utc_offset_secs = atol(off); }
275     }
276     else { /* We've got a working gmtime() */
277       struct tm gmt, local;
278
279       gmt = *tm_p;
280       tm_p = localtime(&base);
281       local = *tm_p;
282       utc_offset_secs  = (local.tm_mday - gmt.tm_mday) * 86400;
283       utc_offset_secs += (local.tm_hour - gmt.tm_hour) * 3600;
284       utc_offset_secs += (local.tm_min  - gmt.tm_min)  * 60;
285       utc_offset_secs += (local.tm_sec  - gmt.tm_sec);
286     }
287   }
288   return 1;
289 }
290
291
292 int
293 gettimeofday (struct timeval *tp, void *tpz)
294 {
295  long ret;
296 #ifdef __VAX
297  long quad[2];
298  long quad1[2];
299  long div_100ns_to_secs;
300  long div_100ns_to_usecs;
301  long quo,rem;
302  long quo1,rem1;
303 #else
304  __int64 quad;
305  __qdiv_t ans1,ans2;
306 #endif
307 /*
308         In case of error, tv_usec = 0 and tv_sec = VMS condition code.
309         The return from function is also set to -1.
310         This is not exactly as per the manual page.
311 */
312
313  tp->tv_usec = 0;
314
315 #ifdef __VAX
316  if (base_adjust[0]==0 && base_adjust[1]==0) {
317 #else
318  if (base_adjust==0) { /* Need to determine epoch adjustment */
319 #endif
320         ret=sys$bintim(&dscepoch,&base_adjust);
321         if (1 != (ret &&1)) {
322                 tp->tv_sec = ret;
323                 return -1;
324         }
325  }
326
327  ret=sys$gettim(&quad); /* Get VMS system time */
328  if ((1 && ret) == 1) {
329 #ifdef __VAX
330         quad[0] -= base_adjust[0]; /* convert to epoch offset */
331         quad[1] -= base_adjust[1]; /* convert 2nd half of quadword */
332         div_100ns_to_secs = DIV_100NS_TO_SECS;
333         div_100ns_to_usecs = DIV_100NS_TO_USECS;
334         lib$ediv(&div_100ns_to_secs,&quad,&quo,&rem);
335         quad1[0] = rem;
336         quad1[1] = 0L;
337         lib$ediv(&div_100ns_to_usecs,&quad1,&quo1,&rem1);
338         tp->tv_sec = quo; /* Whole seconds */
339         tp->tv_usec = quo1; /* Micro-seconds */
340 #else
341         quad -= base_adjust; /* convert to epoch offset */
342         ans1=qdiv(quad,DIV_100NS_TO_SECS);
343         ans2=qdiv(ans1.rem,DIV_100NS_TO_USECS);
344         tp->tv_sec = ans1.quot; /* Whole seconds */
345         tp->tv_usec = ans2.quot; /* Micro-seconds */
346 #endif
347  } else {
348         tp->tv_sec = ret;
349         return -1;
350  }
351 # ifdef VMSISH_TIME
352 # ifdef RTL_USES_UTC
353   if (VMSISH_TIME) tp->tv_sec = _toloc(tp->tv_sec);
354 # else
355   if (!VMSISH_TIME) tp->tv_sec = _toutc(tp->tv_sec);
356 # endif
357 # endif
358  return 0;
359 }
360 #endif
361
362
363  /* Do not use H A S _ N A N O S L E E P
364   * so that Perl Configure doesn't scan for it.
365   * The TIME_HIRES_NANOSLEEP is set by Makefile.PL. */
366 #if !defined(HAS_USLEEP) && defined(TIME_HIRES_NANOSLEEP)
367 #define HAS_USLEEP
368 #define usleep hrt_nanosleep  /* could conflict with ncurses for static build */
369
370 void
371 hrt_nanosleep(unsigned long usec) /* This is used to emulate usleep. */
372 {
373     struct timespec res;
374     res.tv_sec = usec/1000/1000;
375     res.tv_nsec = ( usec - res.tv_sec*1000*1000 ) * 1000;
376     nanosleep(&res, NULL);
377 }
378
379 #endif /* #if !defined(HAS_USLEEP) && defined(TIME_HIRES_NANOSLEEP) */
380
381 #if !defined(HAS_USLEEP) && defined(HAS_SELECT)
382 #ifndef SELECT_IS_BROKEN
383 #define HAS_USLEEP
384 #define usleep hrt_usleep  /* could conflict with ncurses for static build */
385
386 void
387 hrt_usleep(unsigned long usec)
388 {
389     struct timeval tv;
390     tv.tv_sec = 0;
391     tv.tv_usec = usec;
392     select(0, (Select_fd_set_t)NULL, (Select_fd_set_t)NULL,
393                 (Select_fd_set_t)NULL, &tv);
394 }
395 #endif
396 #endif /* #if !defined(HAS_USLEEP) && defined(HAS_SELECT) */
397
398 #if !defined(HAS_USLEEP) && defined(WIN32)
399 #define HAS_USLEEP
400 #define usleep hrt_usleep  /* could conflict with ncurses for static build */
401
402 void
403 hrt_usleep(unsigned long usec)
404 {
405     long msec;
406     msec = usec / 1000;
407     Sleep (msec);
408 }
409 #endif /* #if !defined(HAS_USLEEP) && defined(WIN32) */
410
411
412 #if !defined(HAS_UALARM) && defined(HAS_SETITIMER)
413 #define HAS_UALARM
414 #define ualarm hrt_ualarm  /* could conflict with ncurses for static build */
415
416 int
417 hrt_ualarm(int usec, int interval)
418 {
419    struct itimerval itv;
420    itv.it_value.tv_sec = usec / 1000000;
421    itv.it_value.tv_usec = usec % 1000000;
422    itv.it_interval.tv_sec = interval / 1000000;
423    itv.it_interval.tv_usec = interval % 1000000;
424    return setitimer(ITIMER_REAL, &itv, 0);
425 }
426 #endif /* #if !defined(HAS_UALARM) && defined(HAS_SETITIMER) */
427
428 #if !defined(HAS_UALARM) && defined(VMS)
429 #define HAS_UALARM
430 #define ualarm vms_ualarm 
431
432 #include <lib$routines.h>
433 #include <ssdef.h>
434 #include <starlet.h>
435 #include <descrip.h>
436 #include <signal.h>
437 #include <jpidef.h>
438 #include <psldef.h>
439
440 #define VMSERR(s)   (!((s)&1))
441
442 static void
443 us_to_VMS(useconds_t mseconds, unsigned long v[])
444 {
445     int iss;
446     unsigned long qq[2];
447
448     qq[0] = mseconds;
449     qq[1] = 0;
450     v[0] = v[1] = 0;
451
452     iss = lib$addx(qq,qq,qq);
453     if (VMSERR(iss)) lib$signal(iss);
454     iss = lib$subx(v,qq,v);
455     if (VMSERR(iss)) lib$signal(iss);
456     iss = lib$addx(qq,qq,qq);
457     if (VMSERR(iss)) lib$signal(iss);
458     iss = lib$subx(v,qq,v);
459     if (VMSERR(iss)) lib$signal(iss);
460     iss = lib$subx(v,qq,v);
461     if (VMSERR(iss)) lib$signal(iss);
462 }
463
464 static int
465 VMS_to_us(unsigned long v[])
466 {
467     int iss;
468     unsigned long div=10,quot, rem;
469
470     iss = lib$ediv(&div,v,&quot,&rem);
471     if (VMSERR(iss)) lib$signal(iss);
472
473     return quot;
474 }
475
476 typedef unsigned short word;
477 typedef struct _ualarm {
478     int function;
479     int repeat;
480     unsigned long delay[2];
481     unsigned long interval[2];
482     unsigned long remain[2];
483 } Alarm;
484
485
486 static int alarm_ef;
487 static Alarm *a0, alarm_base;
488 #define UAL_NULL   0
489 #define UAL_SET    1
490 #define UAL_CLEAR  2
491 #define UAL_ACTIVE 4
492 static void ualarm_AST(Alarm *a);
493
494 static int 
495 vms_ualarm(int mseconds, int interval)
496 {
497     Alarm *a, abase;
498     struct item_list3 {
499         word length;
500         word code;
501         void *bufaddr;
502         void *retlenaddr;
503     } ;
504     static struct item_list3 itmlst[2];
505     static int first = 1;
506     unsigned long asten;
507     int iss, enabled;
508
509     if (first) {
510         first = 0;
511         itmlst[0].code       = JPI$_ASTEN;
512         itmlst[0].length     = sizeof(asten);
513         itmlst[0].retlenaddr = NULL;
514         itmlst[1].code       = 0;
515         itmlst[1].length     = 0;
516         itmlst[1].bufaddr    = NULL;
517         itmlst[1].retlenaddr = NULL;
518
519         iss = lib$get_ef(&alarm_ef);
520         if (VMSERR(iss)) lib$signal(iss);
521
522         a0 = &alarm_base;
523         a0->function = UAL_NULL;
524     }
525     itmlst[0].bufaddr    = &asten;
526     
527     iss = sys$getjpiw(0,0,0,itmlst,0,0,0);
528     if (VMSERR(iss)) lib$signal(iss);
529     if (!(asten&0x08)) return -1;
530
531     a = &abase;
532     if (mseconds) {
533         a->function = UAL_SET;
534     } else {
535         a->function = UAL_CLEAR;
536     }
537
538     us_to_VMS(mseconds, a->delay);
539     if (interval) {
540         us_to_VMS(interval, a->interval);
541         a->repeat = 1;
542     } else 
543         a->repeat = 0;
544
545     iss = sys$clref(alarm_ef);
546     if (VMSERR(iss)) lib$signal(iss);
547
548     iss = sys$dclast(ualarm_AST,a,0);
549     if (VMSERR(iss)) lib$signal(iss);
550
551     iss = sys$waitfr(alarm_ef);
552     if (VMSERR(iss)) lib$signal(iss);
553
554     if (a->function == UAL_ACTIVE) 
555         return VMS_to_us(a->remain);
556     else
557         return 0;
558 }
559
560
561
562 static void
563 ualarm_AST(Alarm *a)
564 {
565     int iss;
566     unsigned long now[2];
567
568     iss = sys$gettim(now);
569     if (VMSERR(iss)) lib$signal(iss);
570
571     if (a->function == UAL_SET || a->function == UAL_CLEAR) {
572         if (a0->function == UAL_ACTIVE) {
573             iss = sys$cantim(a0,PSL$C_USER);
574             if (VMSERR(iss)) lib$signal(iss);
575
576             iss = lib$subx(a0->remain, now, a->remain);
577             if (VMSERR(iss)) lib$signal(iss);
578
579             if (a->remain[1] & 0x80000000) 
580                 a->remain[0] = a->remain[1] = 0;
581         }
582
583         if (a->function == UAL_SET) {
584             a->function = a0->function;
585             a0->function = UAL_ACTIVE;
586             a0->repeat = a->repeat;
587             if (a0->repeat) {
588                 a0->interval[0] = a->interval[0];
589                 a0->interval[1] = a->interval[1];
590             }
591             a0->delay[0] = a->delay[0];
592             a0->delay[1] = a->delay[1];
593
594             iss = lib$subx(now, a0->delay, a0->remain);
595             if (VMSERR(iss)) lib$signal(iss);
596
597             iss = sys$setimr(0,a0->delay,ualarm_AST,a0);
598             if (VMSERR(iss)) lib$signal(iss);
599         } else {
600             a->function = a0->function;
601             a0->function = UAL_NULL;
602         }
603         iss = sys$setef(alarm_ef);
604         if (VMSERR(iss)) lib$signal(iss);
605     } else if (a->function == UAL_ACTIVE) {
606         if (a->repeat) {
607             iss = lib$subx(now, a->interval, a->remain);
608             if (VMSERR(iss)) lib$signal(iss);
609
610             iss = sys$setimr(0,a->interval,ualarm_AST,a);
611             if (VMSERR(iss)) lib$signal(iss);
612         } else {
613             a->function = UAL_NULL;
614         }
615         iss = sys$wake(0,0);
616         if (VMSERR(iss)) lib$signal(iss);
617         lib$signal(SS$_ASTFLT);
618     } else {
619         lib$signal(SS$_BADPARAM);
620     }
621 }
622
623 #endif /* #if !defined(HAS_UALARM) && defined(VMS) */
624
625 #ifdef HAS_GETTIMEOFDAY
626
627 static int
628 myU2time(pTHX_ UV *ret)
629 {
630   struct timeval Tp;
631   int status;
632   status = gettimeofday (&Tp, NULL);
633   ret[0] = Tp.tv_sec;
634   ret[1] = Tp.tv_usec;
635   return status;
636 }
637
638 static NV
639 myNVtime()
640 {
641 #ifdef WIN32
642   dTHX;
643 #endif
644   struct timeval Tp;
645   int status;
646   status = gettimeofday (&Tp, NULL);
647   return status == 0 ? Tp.tv_sec + (Tp.tv_usec / 1000000.) : -1.0;
648 }
649
650 #endif /* #ifdef HAS_GETTIMEOFDAY */
651
652 MODULE = Time::HiRes            PACKAGE = Time::HiRes
653
654 PROTOTYPES: ENABLE
655
656 BOOT:
657 {
658 #ifdef MY_CXT_KEY
659   MY_CXT_INIT;
660 #endif
661 #ifdef ATLEASTFIVEOHOHFIVE
662 #ifdef HAS_GETTIMEOFDAY
663   {
664     hv_store(PL_modglobal, "Time::NVtime", 12, newSViv(PTR2IV(myNVtime)), 0);
665     hv_store(PL_modglobal, "Time::U2time", 12, newSViv(PTR2IV(myU2time)), 0);
666   }
667 #endif
668 #endif
669 }
670
671 #if defined(USE_ITHREADS) && defined(MY_CXT_KEY)
672
673 void
674 CLONE(...)
675     CODE:
676     MY_CXT_CLONE;
677
678 #endif
679
680 INCLUDE: const-xs.inc
681
682 #if defined(HAS_USLEEP) && defined(HAS_GETTIMEOFDAY)
683
684 NV
685 usleep(useconds)
686         NV useconds
687         PREINIT:
688         struct timeval Ta, Tb;
689         CODE:
690         gettimeofday(&Ta, NULL);
691         if (items > 0) {
692             if (useconds > 1E6) {
693                 IV seconds = (IV) (useconds / 1E6);
694                 /* If usleep() has been implemented using setitimer()
695                  * then this contortion is unnecessary-- but usleep()
696                  * may be implemented in some other way, so let's contort. */
697                 if (seconds) {
698                     sleep(seconds);
699                     useconds -= 1E6 * seconds;
700                 }
701             } else if (useconds < 0.0)
702                 croak("Time::HiRes::usleep(%"NVgf"): negative time not invented yet", useconds);
703             usleep((U32)useconds);
704         } else
705             PerlProc_pause();
706         gettimeofday(&Tb, NULL);
707 #if 0
708         printf("[%ld %ld] [%ld %ld]\n", Tb.tv_sec, Tb.tv_usec, Ta.tv_sec, Ta.tv_usec);
709 #endif
710         RETVAL = 1E6*(Tb.tv_sec-Ta.tv_sec)+(NV)((IV)Tb.tv_usec-(IV)Ta.tv_usec);
711
712         OUTPUT:
713         RETVAL
714
715 #if defined(TIME_HIRES_NANOSLEEP)
716
717 NV
718 nanosleep(nseconds)
719         NV nseconds
720         PREINIT:
721         struct timeval Ta, Tb;
722         CODE:
723         gettimeofday(&Ta, NULL);
724         if (items > 0) {
725             struct timespec tsa;
726             if (nseconds > 1E9) {
727                 IV seconds = (IV) (nseconds / 1E9);
728                 if (seconds) {
729                     sleep(seconds);
730                     nseconds -= 1E9 * seconds;
731                 }
732             } else if (nseconds < 0.0)
733                 croak("Time::HiRes::nanosleep(%"NVgf"): negative time not invented yet", nseconds);
734             tsa.tv_sec  = (IV) (nseconds / 1E9);
735             tsa.tv_nsec = (IV) nseconds - tsa.tv_sec * 1E9;
736             nanosleep(&tsa, NULL);
737         } else
738             PerlProc_pause();
739         gettimeofday(&Tb, NULL);
740         RETVAL = 1E3*(1E6*(Tb.tv_sec-Ta.tv_sec)+(NV)((IV)Tb.tv_usec-(IV)Ta.tv_usec));
741
742         OUTPUT:
743         RETVAL
744
745 #else  /* #if defined(TIME_HIRES_NANOSLEEP) */
746
747 NV
748 nanosleep(nseconds)
749         NV nseconds
750     CODE:
751         croak("Time::HiRes::nanosleep(): unimplemented in this platform");
752         RETVAL = 0.0;
753
754 #endif /* #if defined(TIME_HIRES_NANOSLEEP) */
755
756 NV
757 sleep(...)
758         PREINIT:
759         struct timeval Ta, Tb;
760         CODE:
761         gettimeofday(&Ta, NULL);
762         if (items > 0) {
763             NV seconds  = SvNV(ST(0));
764             if (seconds >= 0.0) {
765                  UV useconds = (UV)(1E6 * (seconds - (UV)seconds));
766                  if (seconds >= 1.0)
767                      sleep((U32)seconds);
768                  if ((IV)useconds < 0) {
769 #if defined(__sparc64__) && defined(__GNUC__)
770                    /* Sparc64 gcc 2.95.3 (e.g. on NetBSD) has a bug
771                     * where (0.5 - (UV)(0.5)) will under certain
772                     * circumstances (if the double is cast to UV more
773                     * than once?) evaluate to -0.5, instead of 0.5. */
774                    useconds = -(IV)useconds;
775 #endif /* #if defined(__sparc64__) && defined(__GNUC__) */
776                    if ((IV)useconds < 0)
777                      croak("Time::HiRes::sleep(%"NVgf"): internal error: useconds < 0 (unsigned %"UVuf" signed %"IVdf")", seconds, useconds, (IV)useconds);
778                  }
779                  usleep(useconds);
780             } else
781                 croak("Time::HiRes::sleep(%"NVgf"): negative time not invented yet", seconds);
782         } else
783             PerlProc_pause();
784         gettimeofday(&Tb, NULL);
785 #if 0
786         printf("[%ld %ld] [%ld %ld]\n", Tb.tv_sec, Tb.tv_usec, Ta.tv_sec, Ta.tv_usec);
787 #endif
788         RETVAL = (NV)(Tb.tv_sec-Ta.tv_sec)+0.000001*(NV)(Tb.tv_usec-Ta.tv_usec);
789
790         OUTPUT:
791         RETVAL
792
793 #else  /* #if defined(HAS_USLEEP) && defined(HAS_GETTIMEOFDAY) */
794
795 NV
796 usleep(useconds)
797         NV useconds
798     CODE:
799         croak("Time::HiRes::usleep(): unimplemented in this platform");
800         RETVAL = 0.0;
801
802 #endif /* #if defined(HAS_USLEEP) && defined(HAS_GETTIMEOFDAY) */
803
804 #ifdef HAS_UALARM
805
806 int
807 ualarm(useconds,interval=0)
808         int useconds
809         int interval
810         CODE:
811         if (useconds < 0 || interval < 0)
812             croak("Time::HiRes::ualarm(%d, %d): negative time not invented yet", useconds, interval);
813         RETVAL = ualarm(useconds, interval);
814
815         OUTPUT:
816         RETVAL
817
818 NV
819 alarm(seconds,interval=0)
820         NV seconds
821         NV interval
822         CODE:
823         if (seconds < 0.0 || interval < 0.0)
824             croak("Time::HiRes::alarm(%"NVgf", %"NVgf"): negative time not invented yet", seconds, interval);
825         RETVAL = (NV)ualarm(seconds  * 1000000,
826                             interval * 1000000) / 1E6;
827
828         OUTPUT:
829         RETVAL
830
831 #else
832
833 int
834 ualarm(useconds,interval=0)
835         int useconds
836         int interval
837     CODE:
838         croak("Time::HiRes::ualarm(): unimplemented in this platform");
839         RETVAL = -1;
840
841 NV
842 alarm(seconds,interval=0)
843         NV seconds
844         NV interval
845     CODE:
846         croak("Time::HiRes::alarm(): unimplemented in this platform");
847         RETVAL = 0.0;
848
849 #endif /* #ifdef HAS_UALARM */
850
851 #ifdef HAS_GETTIMEOFDAY
852 #    ifdef MACOS_TRADITIONAL    /* fix epoch TZ and use unsigned time_t */
853 void
854 gettimeofday()
855         PREINIT:
856         struct timeval Tp;
857         struct timezone Tz;
858         PPCODE:
859         int status;
860         status = gettimeofday (&Tp, &Tz);
861
862         if (status == 0) {
863              Tp.tv_sec += Tz.tz_minuteswest * 60;       /* adjust for TZ */
864              if (GIMME == G_ARRAY) {
865                  EXTEND(sp, 2);
866                  /* Mac OS (Classic) has unsigned time_t */
867                  PUSHs(sv_2mortal(newSVuv(Tp.tv_sec)));
868                  PUSHs(sv_2mortal(newSViv(Tp.tv_usec)));
869              } else {
870                  EXTEND(sp, 1);
871                  PUSHs(sv_2mortal(newSVnv(Tp.tv_sec + (Tp.tv_usec / 1000000.0))));
872              }
873         }
874
875 NV
876 time()
877         PREINIT:
878         struct timeval Tp;
879         struct timezone Tz;
880         CODE:
881         int status;
882         status = gettimeofday (&Tp, &Tz);
883         if (status == 0) {
884             Tp.tv_sec += Tz.tz_minuteswest * 60;        /* adjust for TZ */
885             RETVAL = Tp.tv_sec + (Tp.tv_usec / 1000000.0);
886         } else {
887             RETVAL = -1.0;
888         }
889         OUTPUT:
890         RETVAL
891
892 #    else       /* MACOS_TRADITIONAL */
893 void
894 gettimeofday()
895         PREINIT:
896         struct timeval Tp;
897         PPCODE:
898         int status;
899         status = gettimeofday (&Tp, NULL);
900         if (status == 0) {
901              if (GIMME == G_ARRAY) {
902                  EXTEND(sp, 2);
903                  PUSHs(sv_2mortal(newSViv(Tp.tv_sec)));
904                  PUSHs(sv_2mortal(newSViv(Tp.tv_usec)));
905              } else {
906                  EXTEND(sp, 1);
907                  PUSHs(sv_2mortal(newSVnv(Tp.tv_sec + (Tp.tv_usec / 1000000.0))));
908              }
909         }
910
911 NV
912 time()
913         PREINIT:
914         struct timeval Tp;
915         CODE:
916         int status;
917         status = gettimeofday (&Tp, NULL);
918         if (status == 0) {
919             RETVAL = Tp.tv_sec + (Tp.tv_usec / 1000000.);
920         } else {
921             RETVAL = -1.0;
922         }
923         OUTPUT:
924         RETVAL
925
926 #    endif      /* MACOS_TRADITIONAL */
927 #endif /* #ifdef HAS_GETTIMEOFDAY */
928
929 #if defined(HAS_GETITIMER) && defined(HAS_SETITIMER)
930
931 #define TV2NV(tv) ((NV)((tv).tv_sec) + 0.000001 * (NV)((tv).tv_usec))
932
933 void
934 setitimer(which, seconds, interval = 0)
935         int which
936         NV seconds
937         NV interval
938     PREINIT:
939         struct itimerval newit;
940         struct itimerval oldit;
941     PPCODE:
942         if (seconds < 0.0 || interval < 0.0)
943             croak("Time::HiRes::setitimer(%"IVdf", %"NVgf", %"NVgf"): negative time not invented yet", (IV)which, seconds, interval);
944         newit.it_value.tv_sec  = seconds;
945         newit.it_value.tv_usec =
946           (seconds  - (NV)newit.it_value.tv_sec)    * 1000000.0;
947         newit.it_interval.tv_sec  = interval;
948         newit.it_interval.tv_usec =
949           (interval - (NV)newit.it_interval.tv_sec) * 1000000.0;
950         if (setitimer(which, &newit, &oldit) == 0) {
951           EXTEND(sp, 1);
952           PUSHs(sv_2mortal(newSVnv(TV2NV(oldit.it_value))));
953           if (GIMME == G_ARRAY) {
954             EXTEND(sp, 1);
955             PUSHs(sv_2mortal(newSVnv(TV2NV(oldit.it_interval))));
956           }
957         }
958
959 void
960 getitimer(which)
961         int which
962     PREINIT:
963         struct itimerval nowit;
964     PPCODE:
965         if (getitimer(which, &nowit) == 0) {
966           EXTEND(sp, 1);
967           PUSHs(sv_2mortal(newSVnv(TV2NV(nowit.it_value))));
968           if (GIMME == G_ARRAY) {
969             EXTEND(sp, 1);
970             PUSHs(sv_2mortal(newSVnv(TV2NV(nowit.it_interval))));
971           }
972         }
973
974 #endif /* #if defined(HAS_GETITIMER) && defined(HAS_SETITIMER) */
975
976 #if defined(TIME_HIRES_CLOCK_GETTIME)
977
978 NV
979 clock_gettime(clock_id = CLOCK_REALTIME)
980         int clock_id
981     PREINIT:
982         struct timespec ts;
983         int status = -1;
984     CODE:
985 #ifdef TIME_HIRES_CLOCK_GETTIME_SYSCALL
986         status = syscall(SYS_clock_gettime, clock_id, &ts);
987 #else
988         status = clock_gettime(clock_id, &ts);
989 #endif
990         RETVAL = status == 0 ? ts.tv_sec + (NV) ts.tv_nsec / (NV) 1e9 : -1;
991
992     OUTPUT:
993         RETVAL
994
995 #else  /* if defined(TIME_HIRES_CLOCK_GETTIME) */
996
997 NV
998 clock_gettime(clock_id = 0)
999         int clock_id
1000     CODE:
1001         croak("Time::HiRes::clock_gettime(): unimplemented in this platform");
1002         RETVAL = 0.0;
1003
1004 #endif /*  #if defined(TIME_HIRES_CLOCK_GETTIME) */
1005
1006 #if defined(TIME_HIRES_CLOCK_GETRES)
1007
1008 NV
1009 clock_getres(clock_id = CLOCK_REALTIME)
1010         int clock_id
1011     PREINIT:
1012         int status = -1;
1013         struct timespec ts;
1014     CODE:
1015 #ifdef TIME_HIRES_CLOCK_GETRES_SYSCALL
1016         status = syscall(SYS_clock_getres, clock_id, &ts);
1017 #else
1018         status = clock_getres(clock_id, &ts);
1019 #endif
1020         RETVAL = status == 0 ? ts.tv_sec + (NV) ts.tv_nsec / (NV) 1e9 : -1;
1021
1022     OUTPUT:
1023         RETVAL
1024
1025 #else  /* if defined(TIME_HIRES_CLOCK_GETRES) */
1026
1027 NV
1028 clock_getres(clock_id = 0)
1029         int clock_id
1030     CODE:
1031         croak("Time::HiRes::clock_getres(): unimplemented in this platform");
1032         RETVAL = 0.0;
1033
1034 #endif /*  #if defined(TIME_HIRES_CLOCK_GETRES) */
1035