3 * Copyright (c) 1996-2002 Douglas E. Wegscheid. All rights reserved.
5 * Copyright (c) 2002-2010 Jarkko Hietaniemi.
8 * Copyright (C) 2011, 2012, 2013 Andrew Main (Zefram) <zefram@fysh.org>
10 * This program is free software; you can redistribute it and/or modify
11 * it under the same terms as Perl itself.
17 #define PERL_NO_GET_CONTEXT
24 #if defined(__CYGWIN__) && defined(HAS_W32API_WINDOWS_H)
25 # include <w32api/windows.h>
26 # define CYGWIN_WITH_W32API
31 # include <sys/time.h>
35 # include <sys/select.h>
38 #if defined(TIME_HIRES_CLOCK_GETTIME_SYSCALL) || defined(TIME_HIRES_CLOCK_GETRES_SYSCALL)
45 #define PERL_VERSION_DECIMAL(r,v,s) (r*1000000 + v*1000 + s)
46 #define PERL_DECIMAL_VERSION \
47 PERL_VERSION_DECIMAL(PERL_REVISION,PERL_VERSION,PERL_SUBVERSION)
48 #define PERL_VERSION_GE(r,v,s) \
49 (PERL_DECIMAL_VERSION >= PERL_VERSION_DECIMAL(r,v,s))
51 #ifndef GCC_DIAG_IGNORE
52 # define GCC_DIAG_IGNORE(x)
53 # define GCC_DIAG_RESTORE
55 #ifndef GCC_DIAG_IGNORE_STMT
56 # define GCC_DIAG_IGNORE_STMT(x) GCC_DIAG_IGNORE(x) NOOP
57 # define GCC_DIAG_RESTORE_STMT GCC_DIAG_RESTORE NOOP
60 /* At least ppport.h 3.13 gets this wrong: one really cannot
61 * have NVgf as anything else than "g" under Perl 5.6.x. */
62 #if PERL_REVISION == 5 && PERL_VERSION == 6
67 #if PERL_VERSION_GE(5,7,3) && !PERL_VERSION_GE(5,10,1)
69 # define SAVEOP() SAVEVPTR(PL_op)
72 #define IV_1E6 1000000
73 #define IV_1E7 10000000
74 #define IV_1E9 1000000000
76 #define NV_1E6 1000000.0
77 #define NV_1E7 10000000.0
78 #define NV_1E9 1000000000.0
80 #ifndef PerlProc_pause
81 # define PerlProc_pause() Pause()
87 # undef Pause /* In case perl.h did it already. */
88 # define Pause() sleep(~0) /* Zzz for a long time. */
91 /* Though the cpp define ITIMER_VIRTUAL is available the functionality
92 * is not supported in Cygwin as of August 2004, ditto for Win32.
93 * Neither are ITIMER_PROF or ITIMER_REALPROF implemented. --jhi
95 #if defined(__CYGWIN__) || defined(WIN32)
96 # undef ITIMER_VIRTUAL
98 # undef ITIMER_REALPROF
101 #ifndef TIME_HIRES_CLOCKID_T
102 typedef int clockid_t;
105 #if defined(TIME_HIRES_CLOCK_GETTIME) && defined(_STRUCT_ITIMERSPEC)
107 /* HP-UX has CLOCK_XXX values but as enums, not as defines.
108 * The only way to detect these would be to test compile for each. */
110 /* However, it seems that at least in HP-UX 11.31 ia64 there *are*
111 * defines for these, so let's try detecting them. */
112 # ifndef CLOCK_REALTIME
113 # define CLOCK_REALTIME CLOCK_REALTIME
114 # define CLOCK_VIRTUAL CLOCK_VIRTUAL
115 # define CLOCK_PROFILE CLOCK_PROFILE
117 # endif /* # ifdef __hpux */
119 #endif /* #if defined(TIME_HIRES_CLOCK_GETTIME) && defined(_STRUCT_ITIMERSPEC) */
121 #if defined(WIN32) || defined(CYGWIN_WITH_W32API)
123 #ifndef HAS_GETTIMEOFDAY
124 # define HAS_GETTIMEOFDAY
127 /* shows up in winsock.h?
135 unsigned __int64 ft_i64;
139 #define MY_CXT_KEY "Time::HiRes_" XS_VERSION
142 unsigned long run_count;
143 unsigned __int64 base_ticks;
144 unsigned __int64 tick_frequency;
145 FT_t base_systime_as_filetime;
146 unsigned __int64 reset_time;
151 /* Number of 100 nanosecond units from 1/1/1601 to 1/1/1970 */
153 # define Const64(x) x##LL
155 # define Const64(x) x##i64
157 #define EPOCH_BIAS Const64(116444736000000000)
161 # define IV_1E6LL 1000000LL /* Needed because of Const64() ##-appends LL (or i64). */
162 # define IV_1E7LL 10000000LL
163 # define IV_1E9LL 1000000000LL
165 # define IV_1E6i64 1000000i64
166 # define IV_1E7i64 10000000i64
167 # define IV_1E9i64 1000000000i64
171 /* NOTE: This does not compute the timezone info (doing so can be expensive,
172 * and appears to be unsupported even by glibc) */
174 /* dMY_CXT needs a Perl context and we don't want to call PERL_GET_CONTEXT
175 for performance reasons */
178 #define gettimeofday(tp, not_used) _gettimeofday(aTHX_ tp, not_used)
180 /* If the performance counter delta drifts more than 0.5 seconds from the
181 * system time then we recalibrate to the system time. This means we may
182 * move *backwards* in time! */
183 #define MAX_PERF_COUNTER_SKEW Const64(5000000) /* 0.5 seconds */
185 /* Reset reading from the performance counter every five minutes.
186 * Many PC clocks just seem to be so bad. */
187 #define MAX_PERF_COUNTER_TICKS Const64(300000000) /* 300 seconds */
190 _gettimeofday(pTHX_ struct timeval *tp, void *not_used)
194 unsigned __int64 ticks;
197 PERL_UNUSED_ARG(not_used);
198 if (MY_CXT.run_count++ == 0 ||
199 MY_CXT.base_systime_as_filetime.ft_i64 > MY_CXT.reset_time) {
200 QueryPerformanceFrequency((LARGE_INTEGER*)&MY_CXT.tick_frequency);
201 QueryPerformanceCounter((LARGE_INTEGER*)&MY_CXT.base_ticks);
202 GetSystemTimeAsFileTime(&MY_CXT.base_systime_as_filetime.ft_val);
203 ft.ft_i64 = MY_CXT.base_systime_as_filetime.ft_i64;
204 MY_CXT.reset_time = ft.ft_i64 + MAX_PERF_COUNTER_TICKS;
208 QueryPerformanceCounter((LARGE_INTEGER*)&ticks);
209 ticks -= MY_CXT.base_ticks;
210 ft.ft_i64 = MY_CXT.base_systime_as_filetime.ft_i64
211 + Const64(IV_1E7) * (ticks / MY_CXT.tick_frequency)
212 +(Const64(IV_1E7) * (ticks % MY_CXT.tick_frequency)) / MY_CXT.tick_frequency;
213 diff = ft.ft_i64 - MY_CXT.base_systime_as_filetime.ft_i64;
214 if (diff < -MAX_PERF_COUNTER_SKEW || diff > MAX_PERF_COUNTER_SKEW) {
215 MY_CXT.base_ticks += ticks;
216 GetSystemTimeAsFileTime(&MY_CXT.base_systime_as_filetime.ft_val);
217 ft.ft_i64 = MY_CXT.base_systime_as_filetime.ft_i64;
221 /* seconds since epoch */
222 tp->tv_sec = (long)((ft.ft_i64 - EPOCH_BIAS) / Const64(IV_1E7));
224 /* microseconds remaining */
225 tp->tv_usec = (long)((ft.ft_i64 / Const64(10)) % Const64(IV_1E6));
231 #if defined(WIN32) && !defined(ATLEASTFIVEOHOHFIVE)
233 sleep(unsigned int t)
240 #if !defined(HAS_GETTIMEOFDAY) && defined(VMS)
241 #define HAS_GETTIMEOFDAY
244 #include <time.h> /* gettimeofday */
245 #include <stdlib.h> /* qdiv */
246 #include <starlet.h> /* sys$gettim */
249 #include <lib$routines.h> /* lib$ediv() */
253 VMS binary time is expressed in 100 nano-seconds since
254 system base time which is 17-NOV-1858 00:00:00.00
257 #define DIV_100NS_TO_SECS 10000000L
258 #define DIV_100NS_TO_USECS 10L
261 gettimeofday is supposed to return times since the epoch
262 so need to determine this in terms of VMS base time
264 static $DESCRIPTOR(dscepoch,"01-JAN-1970 00:00:00.00");
267 static long base_adjust[2]={0L,0L};
269 static __int64 base_adjust=0;
274 If we don't have gettimeofday, then likely we are on a VMS machine that
275 operates on local time rather than UTC...so we have to zone-adjust.
276 This code gleefully swiped from VMS.C
279 /* method used to handle UTC conversions:
280 * 1 == CRTL gmtime(); 2 == SYS$TIMEZONE_DIFFERENTIAL; 3 == no correction
282 static int gmtime_emulation_type;
283 /* number of secs to add to UTC POSIX-style time to get local time */
284 static long int utc_offset_secs;
285 static struct dsc$descriptor_s fildevdsc =
286 { 12, DSC$K_DTYPE_T, DSC$K_CLASS_S, "LNM$FILE_DEV" };
287 static struct dsc$descriptor_s *fildev[] = { &fildevdsc, NULL };
289 static time_t toutc_dst(time_t loc) {
292 if ((rsltmp = localtime(&loc)) == NULL) return -1;
293 loc -= utc_offset_secs;
294 if (rsltmp->tm_isdst) loc -= 3600;
298 static time_t toloc_dst(time_t utc) {
301 utc += utc_offset_secs;
302 if ((rsltmp = localtime(&utc)) == NULL) return -1;
303 if (rsltmp->tm_isdst) utc += 3600;
307 #define _toutc(secs) ((secs) == (time_t) -1 ? (time_t) -1 : \
308 ((gmtime_emulation_type || timezone_setup()), \
309 (gmtime_emulation_type == 1 ? toutc_dst(secs) : \
310 ((secs) - utc_offset_secs))))
312 #define _toloc(secs) ((secs) == (time_t) -1 ? (time_t) -1 : \
313 ((gmtime_emulation_type || timezone_setup()), \
314 (gmtime_emulation_type == 1 ? toloc_dst(secs) : \
315 ((secs) + utc_offset_secs))))
322 if (gmtime_emulation_type == 0) {
324 time_t base = 15 * 86400; /* 15jan71; to avoid month/year ends between */
325 /* results of calls to gmtime() and localtime() */
328 gmtime_emulation_type++;
329 if ((tm_p = gmtime(&base)) == NULL) { /* CRTL gmtime() is a fake */
330 char off[LNM$C_NAMLENGTH+1];;
332 gmtime_emulation_type++;
333 if (!Perl_vmstrnenv("SYS$TIMEZONE_DIFFERENTIAL",off,0,fildev,0)) {
334 gmtime_emulation_type++;
336 Perl_warn(aTHX_ "no UTC offset information; assuming local time is UTC");
338 else { utc_offset_secs = atol(off); }
340 else { /* We've got a working gmtime() */
341 struct tm gmt, local;
344 tm_p = localtime(&base);
346 utc_offset_secs = (local.tm_mday - gmt.tm_mday) * 86400;
347 utc_offset_secs += (local.tm_hour - gmt.tm_hour) * 3600;
348 utc_offset_secs += (local.tm_min - gmt.tm_min) * 60;
349 utc_offset_secs += (local.tm_sec - gmt.tm_sec);
357 gettimeofday (struct timeval *tp, void *tpz)
363 long div_100ns_to_secs;
364 long div_100ns_to_usecs;
372 In case of error, tv_usec = 0 and tv_sec = VMS condition code.
373 The return from function is also set to -1.
374 This is not exactly as per the manual page.
380 if (base_adjust[0]==0 && base_adjust[1]==0) {
382 if (base_adjust==0) { /* Need to determine epoch adjustment */
384 ret=sys$bintim(&dscepoch,&base_adjust);
385 if (1 != (ret &&1)) {
391 ret=sys$gettim(&quad); /* Get VMS system time */
392 if ((1 && ret) == 1) {
394 quad[0] -= base_adjust[0]; /* convert to epoch offset */
395 quad[1] -= base_adjust[1]; /* convert 2nd half of quadword */
396 div_100ns_to_secs = DIV_100NS_TO_SECS;
397 div_100ns_to_usecs = DIV_100NS_TO_USECS;
398 lib$ediv(&div_100ns_to_secs,&quad,&quo,&rem);
401 lib$ediv(&div_100ns_to_usecs,&quad1,&quo1,&rem1);
402 tp->tv_sec = quo; /* Whole seconds */
403 tp->tv_usec = quo1; /* Micro-seconds */
405 quad -= base_adjust; /* convert to epoch offset */
406 ans1=qdiv(quad,DIV_100NS_TO_SECS);
407 ans2=qdiv(ans1.rem,DIV_100NS_TO_USECS);
408 tp->tv_sec = ans1.quot; /* Whole seconds */
409 tp->tv_usec = ans2.quot; /* Micro-seconds */
417 if (VMSISH_TIME) tp->tv_sec = _toloc(tp->tv_sec);
419 if (!VMSISH_TIME) tp->tv_sec = _toutc(tp->tv_sec);
427 /* Do not use H A S _ N A N O S L E E P
428 * so that Perl Configure doesn't scan for it (and pull in -lrt and
429 * the like which are not usually good ideas for the default Perl).
430 * (We are part of the core perl now.)
431 * The TIME_HIRES_NANOSLEEP is set by Makefile.PL. */
432 #if !defined(HAS_USLEEP) && defined(TIME_HIRES_NANOSLEEP)
434 #define usleep hrt_usleep /* could conflict with ncurses for static build */
437 hrt_usleep(unsigned long usec) /* This is used to emulate usleep. */
440 res.tv_sec = usec / IV_1E6;
441 res.tv_nsec = ( usec - res.tv_sec * IV_1E6 ) * 1000;
442 nanosleep(&res, NULL);
445 #endif /* #if !defined(HAS_USLEEP) && defined(TIME_HIRES_NANOSLEEP) */
447 #if !defined(HAS_USLEEP) && defined(HAS_SELECT)
448 #ifndef SELECT_IS_BROKEN
450 #define usleep hrt_usleep /* could conflict with ncurses for static build */
453 hrt_usleep(unsigned long usec)
458 select(0, (Select_fd_set_t)NULL, (Select_fd_set_t)NULL,
459 (Select_fd_set_t)NULL, &tv);
462 #endif /* #if !defined(HAS_USLEEP) && defined(HAS_SELECT) */
464 #if !defined(HAS_USLEEP) && defined(WIN32)
466 #define usleep hrt_usleep /* could conflict with ncurses for static build */
469 hrt_usleep(unsigned long usec)
475 #endif /* #if !defined(HAS_USLEEP) && defined(WIN32) */
477 #if !defined(HAS_USLEEP) && defined(HAS_POLL)
479 #define usleep hrt_usleep /* could conflict with ncurses for static build */
482 hrt_usleep(unsigned long usec)
484 int msec = usec / 1000;
488 #endif /* #if !defined(HAS_USLEEP) && defined(HAS_POLL) */
490 #if defined(HAS_SETITIMER) && defined(ITIMER_REAL)
493 hrt_ualarm_itimero(struct itimerval *oitv, int usec, int uinterval)
495 struct itimerval itv;
496 itv.it_value.tv_sec = usec / IV_1E6;
497 itv.it_value.tv_usec = usec % IV_1E6;
498 itv.it_interval.tv_sec = uinterval / IV_1E6;
499 itv.it_interval.tv_usec = uinterval % IV_1E6;
500 return setitimer(ITIMER_REAL, &itv, oitv);
503 #endif /* #if !defined(HAS_UALARM) && defined(HAS_SETITIMER) */
505 #if !defined(HAS_UALARM) && defined(HAS_SETITIMER)
507 #define ualarm hrt_ualarm_itimer /* could conflict with ncurses for static build */
510 #if !defined(HAS_UALARM) && defined(VMS)
512 #define ualarm vms_ualarm
514 #include <lib$routines.h>
522 #define VMSERR(s) (!((s)&1))
525 us_to_VMS(useconds_t mseconds, unsigned long v[])
534 iss = lib$addx(qq,qq,qq);
535 if (VMSERR(iss)) lib$signal(iss);
536 iss = lib$subx(v,qq,v);
537 if (VMSERR(iss)) lib$signal(iss);
538 iss = lib$addx(qq,qq,qq);
539 if (VMSERR(iss)) lib$signal(iss);
540 iss = lib$subx(v,qq,v);
541 if (VMSERR(iss)) lib$signal(iss);
542 iss = lib$subx(v,qq,v);
543 if (VMSERR(iss)) lib$signal(iss);
547 VMS_to_us(unsigned long v[])
550 unsigned long div=10,quot, rem;
552 iss = lib$ediv(&div,v,",&rem);
553 if (VMSERR(iss)) lib$signal(iss);
558 typedef unsigned short word;
559 typedef struct _ualarm {
562 unsigned long delay[2];
563 unsigned long interval[2];
564 unsigned long remain[2];
569 static Alarm *a0, alarm_base;
574 static void ualarm_AST(Alarm *a);
577 vms_ualarm(int mseconds, int interval)
586 static struct item_list3 itmlst[2];
587 static int first = 1;
593 itmlst[0].code = JPI$_ASTEN;
594 itmlst[0].length = sizeof(asten);
595 itmlst[0].retlenaddr = NULL;
597 itmlst[1].length = 0;
598 itmlst[1].bufaddr = NULL;
599 itmlst[1].retlenaddr = NULL;
601 iss = lib$get_ef(&alarm_ef);
602 if (VMSERR(iss)) lib$signal(iss);
605 a0->function = UAL_NULL;
607 itmlst[0].bufaddr = &asten;
609 iss = sys$getjpiw(0,0,0,itmlst,0,0,0);
610 if (VMSERR(iss)) lib$signal(iss);
611 if (!(asten&0x08)) return -1;
615 a->function = UAL_SET;
617 a->function = UAL_CLEAR;
620 us_to_VMS(mseconds, a->delay);
622 us_to_VMS(interval, a->interval);
627 iss = sys$clref(alarm_ef);
628 if (VMSERR(iss)) lib$signal(iss);
630 iss = sys$dclast(ualarm_AST,a,0);
631 if (VMSERR(iss)) lib$signal(iss);
633 iss = sys$waitfr(alarm_ef);
634 if (VMSERR(iss)) lib$signal(iss);
636 if (a->function == UAL_ACTIVE)
637 return VMS_to_us(a->remain);
648 unsigned long now[2];
650 iss = sys$gettim(now);
651 if (VMSERR(iss)) lib$signal(iss);
653 if (a->function == UAL_SET || a->function == UAL_CLEAR) {
654 if (a0->function == UAL_ACTIVE) {
655 iss = sys$cantim(a0,PSL$C_USER);
656 if (VMSERR(iss)) lib$signal(iss);
658 iss = lib$subx(a0->remain, now, a->remain);
659 if (VMSERR(iss)) lib$signal(iss);
661 if (a->remain[1] & 0x80000000)
662 a->remain[0] = a->remain[1] = 0;
665 if (a->function == UAL_SET) {
666 a->function = a0->function;
667 a0->function = UAL_ACTIVE;
668 a0->repeat = a->repeat;
670 a0->interval[0] = a->interval[0];
671 a0->interval[1] = a->interval[1];
673 a0->delay[0] = a->delay[0];
674 a0->delay[1] = a->delay[1];
676 iss = lib$subx(now, a0->delay, a0->remain);
677 if (VMSERR(iss)) lib$signal(iss);
679 iss = sys$setimr(0,a0->delay,ualarm_AST,a0);
680 if (VMSERR(iss)) lib$signal(iss);
682 a->function = a0->function;
683 a0->function = UAL_NULL;
685 iss = sys$setef(alarm_ef);
686 if (VMSERR(iss)) lib$signal(iss);
687 } else if (a->function == UAL_ACTIVE) {
689 iss = lib$subx(now, a->interval, a->remain);
690 if (VMSERR(iss)) lib$signal(iss);
692 iss = sys$setimr(0,a->interval,ualarm_AST,a);
693 if (VMSERR(iss)) lib$signal(iss);
695 a->function = UAL_NULL;
698 if (VMSERR(iss)) lib$signal(iss);
699 lib$signal(SS$_ASTFLT);
701 lib$signal(SS$_BADPARAM);
705 #endif /* #if !defined(HAS_UALARM) && defined(VMS) */
707 #ifdef HAS_GETTIMEOFDAY
710 myU2time(pTHX_ UV *ret)
714 status = gettimeofday (&Tp, NULL);
728 status = gettimeofday (&Tp, NULL);
729 return status == 0 ? Tp.tv_sec + (Tp.tv_usec / NV_1E6) : -1.0;
732 #endif /* #ifdef HAS_GETTIMEOFDAY */
735 hrstatns(UV *atime_nsec, UV *mtime_nsec, UV *ctime_nsec)
738 #if TIME_HIRES_STAT == 1
739 *atime_nsec = PL_statcache.st_atimespec.tv_nsec;
740 *mtime_nsec = PL_statcache.st_mtimespec.tv_nsec;
741 *ctime_nsec = PL_statcache.st_ctimespec.tv_nsec;
742 #elif TIME_HIRES_STAT == 2
743 *atime_nsec = PL_statcache.st_atimensec;
744 *mtime_nsec = PL_statcache.st_mtimensec;
745 *ctime_nsec = PL_statcache.st_ctimensec;
746 #elif TIME_HIRES_STAT == 3
747 *atime_nsec = PL_statcache.st_atime_n;
748 *mtime_nsec = PL_statcache.st_mtime_n;
749 *ctime_nsec = PL_statcache.st_ctime_n;
750 #elif TIME_HIRES_STAT == 4
751 *atime_nsec = PL_statcache.st_atim.tv_nsec;
752 *mtime_nsec = PL_statcache.st_mtim.tv_nsec;
753 *ctime_nsec = PL_statcache.st_ctim.tv_nsec;
754 #elif TIME_HIRES_STAT == 5
755 *atime_nsec = PL_statcache.st_uatime * 1000;
756 *mtime_nsec = PL_statcache.st_umtime * 1000;
757 *ctime_nsec = PL_statcache.st_uctime * 1000;
758 #else /* !TIME_HIRES_STAT */
762 #endif /* !TIME_HIRES_STAT */
765 /* Until Apple implements clock_gettime()
766 * (ditto clock_getres() and clock_nanosleep())
767 * we will emulate them using the Mach kernel interfaces. */
768 #if defined(PERL_DARWIN) && \
769 (defined(TIME_HIRES_CLOCK_GETTIME_EMULATION) || \
770 defined(TIME_HIRES_CLOCK_GETRES_EMULATION) || \
771 defined(TIME_HIRES_CLOCK_NANOSLEEP_EMULATION))
773 #ifndef CLOCK_REALTIME
774 # define CLOCK_REALTIME 0x01
775 # define CLOCK_MONOTONIC 0x02
778 #ifndef TIMER_ABSTIME
779 # define TIMER_ABSTIME 0x01
783 # define PERL_DARWIN_MUTEX
786 #ifdef PERL_DARWIN_MUTEX
787 STATIC perl_mutex darwin_time_mutex;
790 #include <mach/mach_time.h>
792 static uint64_t absolute_time_init;
793 static mach_timebase_info_data_t timebase_info;
794 static struct timespec timespec_init;
796 static int darwin_time_init() {
799 #ifdef PERL_DARWIN_MUTEX
800 MUTEX_LOCK(&darwin_time_mutex);
802 if (absolute_time_init == 0) {
803 /* mach_absolute_time() cannot fail */
804 absolute_time_init = mach_absolute_time();
805 success = mach_timebase_info(&timebase_info) == KERN_SUCCESS;
807 success = gettimeofday(&tv, NULL) == 0;
809 timespec_init.tv_sec = tv.tv_sec;
810 timespec_init.tv_nsec = tv.tv_usec * 1000;
814 #ifdef PERL_DARWIN_MUTEX
815 MUTEX_UNLOCK(&darwin_time_mutex);
820 #ifdef TIME_HIRES_CLOCK_GETTIME_EMULATION
821 static int th_clock_gettime(clockid_t clock_id, struct timespec *ts) {
822 if (darwin_time_init() && timebase_info.denom) {
827 ((mach_absolute_time() - absolute_time_init) *
828 (uint64_t)timebase_info.numer) / (uint64_t)timebase_info.denom;
829 ts->tv_sec = timespec_init.tv_sec + nanos / IV_1E9;
830 ts->tv_nsec = timespec_init.tv_nsec + nanos % IV_1E9;
834 case CLOCK_MONOTONIC:
837 (mach_absolute_time() *
838 (uint64_t)timebase_info.numer) / (uint64_t)timebase_info.denom;
839 ts->tv_sec = nanos / IV_1E9;
840 ts->tv_nsec = nanos - ts->tv_sec * IV_1E9;
849 SETERRNO(EINVAL, LIB_INVARG);
853 #define clock_gettime(clock_id, ts) th_clock_gettime((clock_id), (ts))
855 #endif /* TIME_HIRES_CLOCK_GETTIME_EMULATION */
857 #ifdef TIME_HIRES_CLOCK_GETRES_EMULATION
858 static int th_clock_getres(clockid_t clock_id, struct timespec *ts) {
859 if (darwin_time_init() && timebase_info.denom) {
862 case CLOCK_MONOTONIC:
864 /* In newer kernels both the numer and denom are one,
865 * resulting in conversion factor of one, which is of
866 * course unrealistic. */
867 ts->tv_nsec = timebase_info.numer / timebase_info.denom;
874 SETERRNO(EINVAL, LIB_INVARG);
878 #define clock_getres(clock_id, ts) th_clock_getres((clock_id), (ts))
879 #endif /* TIME_HIRES_CLOCK_GETRES_EMULATION */
881 #ifdef TIME_HIRES_CLOCK_NANOSLEEP_EMULATION
882 static int th_clock_nanosleep(clockid_t clock_id, int flags,
883 const struct timespec *rqtp,
884 struct timespec *rmtp) {
885 if (darwin_time_init()) {
888 case CLOCK_MONOTONIC:
890 uint64_t nanos = rqtp->tv_sec * IV_1E9 + rqtp->tv_nsec;
892 if ((flags & TIMER_ABSTIME)) {
894 timespec_init.tv_sec * IV_1E9 + timespec_init.tv_nsec;
895 nanos = nanos > back ? nanos - back : 0;
898 mach_wait_until(mach_absolute_time() + nanos) == KERN_SUCCESS;
900 /* In the relative sleep, the rmtp should be filled in with
901 * the 'unused' part of the rqtp in case the sleep gets
902 * interrupted by a signal. But it is unknown how signals
903 * interact with mach_wait_until(). In the absolute sleep,
904 * the rmtp should stay untouched. */
916 SETERRNO(EINVAL, LIB_INVARG);
920 #define clock_nanosleep(clock_id, flags, rqtp, rmtp) \
921 th_clock_nanosleep((clock_id), (flags), (rqtp), (rmtp))
923 #endif /* TIME_HIRES_CLOCK_NANOSLEEP_EMULATION */
925 #endif /* PERL_DARWIN */
927 /* The macOS headers warn about using certain interfaces in
928 * OS-release-ignorant manner, for example:
930 * warning: 'futimens' is only available on macOS 10.13 or newer
931 * [-Wunguarded-availability-new]
933 * (ditto for utimensat)
935 * There is clang __builtin_available() *runtime* check for this.
936 * The gotchas are that neither __builtin_available() nor __has_builtin()
937 * are always available.
939 #ifndef __has_builtin
940 # define __has_builtin(x) 0 /* non-clang */
943 # if defined(PERL_DARWIN) && __has_builtin(__builtin_available)
944 # define FUTIMENS_AVAILABLE __builtin_available(macOS 10.13, *)
946 # define FUTIMENS_AVAILABLE 1
949 # define FUTIMENS_AVAILABLE 0
952 # if defined(PERL_DARWIN) && __has_builtin(__builtin_available)
953 # define UTIMENSAT_AVAILABLE __builtin_available(macOS 10.13, *)
955 # define UTIMENSAT_AVAILABLE 1
958 # define UTIMENSAT_AVAILABLE 0
961 #include "const-c.inc"
963 #if (defined(TIME_HIRES_NANOSLEEP)) || \
964 (defined(TIME_HIRES_CLOCK_NANOSLEEP) && defined(TIMER_ABSTIME))
967 nanosleep_init(NV nsec,
968 struct timespec *sleepfor,
969 struct timespec *unslept) {
970 sleepfor->tv_sec = (Time_t)(nsec / NV_1E9);
971 sleepfor->tv_nsec = (long)(nsec - ((NV)sleepfor->tv_sec) * NV_1E9);
973 unslept->tv_nsec = 0;
977 nsec_without_unslept(struct timespec *sleepfor,
978 const struct timespec *unslept) {
979 if (sleepfor->tv_sec >= unslept->tv_sec) {
980 sleepfor->tv_sec -= unslept->tv_sec;
981 if (sleepfor->tv_nsec >= unslept->tv_nsec) {
982 sleepfor->tv_nsec -= unslept->tv_nsec;
983 } else if (sleepfor->tv_sec > 0) {
985 sleepfor->tv_nsec += IV_1E9;
986 sleepfor->tv_nsec -= unslept->tv_nsec;
988 sleepfor->tv_sec = 0;
989 sleepfor->tv_nsec = 0;
992 sleepfor->tv_sec = 0;
993 sleepfor->tv_nsec = 0;
995 return ((NV)sleepfor->tv_sec) * NV_1E9 + ((NV)sleepfor->tv_nsec);
1000 /* In case Perl and/or Devel::PPPort are too old, minimally emulate
1001 * IS_SAFE_PATHNAME() (which looks for zero bytes in the pathname). */
1002 #ifndef IS_SAFE_PATHNAME
1003 #if PERL_VERSION >= 12 /* Perl_ck_warner is 5.10.0 -> */
1004 #ifdef WARN_SYSCALLS
1005 #define WARNEMUCAT WARN_SYSCALLS /* 5.22.0 -> */
1007 #define WARNEMUCAT WARN_MISC
1009 #define WARNEMU(opname) Perl_ck_warner(aTHX_ packWARN(WARNEMUCAT), "Invalid \\0 character in pathname for %s",opname)
1011 #define WARNEMU(opname) Perl_warn(aTHX_ "Invalid \\0 character in pathname for %s",opname)
1013 #define IS_SAFE_PATHNAME(pv, len, opname) (((len)>1)&&memchr((pv), 0, (len)-1)?(SETERRNO(ENOENT, LIB_INVARG),WARNEMU(opname),FALSE):(TRUE))
1016 MODULE = Time::HiRes PACKAGE = Time::HiRes
1025 #ifdef ATLEASTFIVEOHOHFIVE
1026 # ifdef HAS_GETTIMEOFDAY
1028 (void) hv_store(PL_modglobal, "Time::NVtime", 12,
1029 newSViv(PTR2IV(myNVtime)), 0);
1030 (void) hv_store(PL_modglobal, "Time::U2time", 12,
1031 newSViv(PTR2IV(myU2time)), 0);
1035 #if defined(PERL_DARWIN)
1036 # if defined(USE_ITHREADS) && defined(PERL_DARWIN_MUTEX)
1037 MUTEX_INIT(&darwin_time_mutex);
1042 #if defined(USE_ITHREADS) && defined(MY_CXT_KEY)
1051 INCLUDE: const-xs.inc
1053 #if defined(HAS_USLEEP) && defined(HAS_GETTIMEOFDAY)
1059 struct timeval Ta, Tb;
1061 gettimeofday(&Ta, NULL);
1063 if (useconds >= NV_1E6) {
1064 IV seconds = (IV) (useconds / NV_1E6);
1065 /* If usleep() has been implemented using setitimer()
1066 * then this contortion is unnecessary-- but usleep()
1067 * may be implemented in some other way, so let's contort. */
1070 useconds -= NV_1E6 * seconds;
1072 } else if (useconds < 0.0)
1073 croak("Time::HiRes::usleep(%" NVgf
1074 "): negative time not invented yet", useconds);
1075 usleep((U32)useconds);
1078 gettimeofday(&Tb, NULL);
1080 printf("[%ld %ld] [%ld %ld]\n", Tb.tv_sec, Tb.tv_usec, Ta.tv_sec, Ta.tv_usec);
1082 RETVAL = NV_1E6*(Tb.tv_sec-Ta.tv_sec)+(NV)((IV)Tb.tv_usec-(IV)Ta.tv_usec);
1087 #if defined(TIME_HIRES_NANOSLEEP)
1093 struct timespec sleepfor, unslept;
1096 croak("Time::HiRes::nanosleep(%" NVgf
1097 "): negative time not invented yet", nsec);
1098 nanosleep_init(nsec, &sleepfor, &unslept);
1099 if (nanosleep(&sleepfor, &unslept) == 0) {
1102 RETVAL = nsec_without_unslept(&sleepfor, &unslept);
1107 #else /* #if defined(TIME_HIRES_NANOSLEEP) */
1113 PERL_UNUSED_ARG(nsec);
1114 croak("Time::HiRes::nanosleep(): unimplemented in this platform");
1119 #endif /* #if defined(TIME_HIRES_NANOSLEEP) */
1124 struct timeval Ta, Tb;
1126 gettimeofday(&Ta, NULL);
1128 NV seconds = SvNV(ST(0));
1129 if (seconds >= 0.0) {
1130 UV useconds = (UV)(1E6 * (seconds - (UV)seconds));
1132 sleep((U32)seconds);
1133 if ((IV)useconds < 0) {
1134 #if defined(__sparc64__) && defined(__GNUC__)
1135 /* Sparc64 gcc 2.95.3 (e.g. on NetBSD) has a bug
1136 * where (0.5 - (UV)(0.5)) will under certain
1137 * circumstances (if the double is cast to UV more
1138 * than once?) evaluate to -0.5, instead of 0.5. */
1139 useconds = -(IV)useconds;
1140 #endif /* #if defined(__sparc64__) && defined(__GNUC__) */
1141 if ((IV)useconds < 0)
1142 croak("Time::HiRes::sleep(%" NVgf
1143 "): internal error: useconds < 0 (unsigned %" UVuf
1144 " signed %" IVdf ")",
1145 seconds, useconds, (IV)useconds);
1149 croak("Time::HiRes::sleep(%" NVgf
1150 "): negative time not invented yet", seconds);
1153 gettimeofday(&Tb, NULL);
1155 printf("[%ld %ld] [%ld %ld]\n", Tb.tv_sec, Tb.tv_usec, Ta.tv_sec, Ta.tv_usec);
1157 RETVAL = (NV)(Tb.tv_sec-Ta.tv_sec)+0.000001*(NV)(Tb.tv_usec-Ta.tv_usec);
1162 #else /* #if defined(HAS_USLEEP) && defined(HAS_GETTIMEOFDAY) */
1168 PERL_UNUSED_ARG(useconds);
1169 croak("Time::HiRes::usleep(): unimplemented in this platform");
1174 #endif /* #if defined(HAS_USLEEP) && defined(HAS_GETTIMEOFDAY) */
1179 ualarm(useconds,uinterval=0)
1183 if (useconds < 0 || uinterval < 0)
1184 croak("Time::HiRes::ualarm(%d, %d): negative time not invented yet", useconds, uinterval);
1185 #if defined(HAS_SETITIMER) && defined(ITIMER_REAL)
1187 struct itimerval itv;
1188 if (hrt_ualarm_itimero(&itv, useconds, uinterval)) {
1189 /* To conform to ualarm's interface, we're actually ignoring
1193 RETVAL = itv.it_value.tv_sec * IV_1E6 + itv.it_value.tv_usec;
1197 if (useconds >= IV_1E6 || uinterval >= IV_1E6)
1198 croak("Time::HiRes::ualarm(%d, %d): useconds or uinterval"
1199 " equal to or more than %" IVdf,
1200 useconds, uinterval, IV_1E6);
1201 RETVAL = ualarm(useconds, uinterval);
1208 alarm(seconds,interval=0)
1212 if (seconds < 0.0 || interval < 0.0)
1213 croak("Time::HiRes::alarm(%" NVgf ", %" NVgf
1214 "): negative time not invented yet", seconds, interval);
1216 IV iseconds = (IV)seconds;
1217 IV iinterval = (IV)interval;
1218 NV fseconds = seconds - iseconds;
1219 NV finterval = interval - iinterval;
1220 IV useconds, uinterval;
1221 if (fseconds >= 1.0 || finterval >= 1.0)
1222 croak("Time::HiRes::alarm(%" NVgf ", %" NVgf
1223 "): seconds or interval too large to split correctly",
1225 useconds = IV_1E6 * fseconds;
1226 uinterval = IV_1E6 * finterval;
1227 #if defined(HAS_SETITIMER) && defined(ITIMER_REAL)
1229 struct itimerval nitv, oitv;
1230 nitv.it_value.tv_sec = iseconds;
1231 nitv.it_value.tv_usec = useconds;
1232 nitv.it_interval.tv_sec = iinterval;
1233 nitv.it_interval.tv_usec = uinterval;
1234 if (setitimer(ITIMER_REAL, &nitv, &oitv)) {
1235 /* To conform to alarm's interface, we're actually ignoring
1239 RETVAL = oitv.it_value.tv_sec + ((NV)oitv.it_value.tv_usec) / NV_1E6;
1243 if (iseconds || iinterval)
1244 croak("Time::HiRes::alarm(%" NVgf ", %" NVgf
1245 "): seconds or interval equal to or more than 1.0 ",
1247 RETVAL = (NV)ualarm( useconds, uinterval ) / NV_1E6;
1257 ualarm(useconds,interval=0)
1261 PERL_UNUSED_ARG(useconds);
1262 PERL_UNUSED_ARG(interval);
1263 croak("Time::HiRes::ualarm(): unimplemented in this platform");
1269 alarm(seconds,interval=0)
1273 PERL_UNUSED_ARG(seconds);
1274 PERL_UNUSED_ARG(interval);
1275 croak("Time::HiRes::alarm(): unimplemented in this platform");
1280 #endif /* #ifdef HAS_UALARM */
1282 #ifdef HAS_GETTIMEOFDAY
1283 # ifdef MACOS_TRADITIONAL /* fix epoch TZ and use unsigned time_t */
1291 status = gettimeofday (&Tp, &Tz);
1294 Tp.tv_sec += Tz.tz_minuteswest * 60; /* adjust for TZ */
1295 if (GIMME == G_ARRAY) {
1297 /* Mac OS (Classic) has unsigned time_t */
1298 PUSHs(sv_2mortal(newSVuv(Tp.tv_sec)));
1299 PUSHs(sv_2mortal(newSViv(Tp.tv_usec)));
1302 PUSHs(sv_2mortal(newSVnv(Tp.tv_sec + (Tp.tv_usec / NV_1E6))));
1313 status = gettimeofday (&Tp, &Tz);
1315 Tp.tv_sec += Tz.tz_minuteswest * 60; /* adjust for TZ */
1316 RETVAL = Tp.tv_sec + (Tp.tv_usec / NV_1E6);
1323 # else /* MACOS_TRADITIONAL */
1330 status = gettimeofday (&Tp, NULL);
1332 if (GIMME == G_ARRAY) {
1334 PUSHs(sv_2mortal(newSViv(Tp.tv_sec)));
1335 PUSHs(sv_2mortal(newSViv(Tp.tv_usec)));
1338 PUSHs(sv_2mortal(newSVnv(Tp.tv_sec + (Tp.tv_usec / NV_1E6))));
1348 status = gettimeofday (&Tp, NULL);
1350 RETVAL = Tp.tv_sec + (Tp.tv_usec / NV_1E6);
1357 # endif /* MACOS_TRADITIONAL */
1358 #endif /* #ifdef HAS_GETTIMEOFDAY */
1360 #if defined(HAS_GETITIMER) && defined(HAS_SETITIMER)
1362 #define TV2NV(tv) ((NV)((tv).tv_sec) + 0.000001 * (NV)((tv).tv_usec))
1365 setitimer(which, seconds, interval = 0)
1370 struct itimerval newit;
1371 struct itimerval oldit;
1373 if (seconds < 0.0 || interval < 0.0)
1374 croak("Time::HiRes::setitimer(%" IVdf ", %" NVgf ", %" NVgf
1375 "): negative time not invented yet",
1376 (IV)which, seconds, interval);
1377 newit.it_value.tv_sec = (IV)seconds;
1378 newit.it_value.tv_usec =
1379 (IV)((seconds - (NV)newit.it_value.tv_sec) * NV_1E6);
1380 newit.it_interval.tv_sec = (IV)interval;
1381 newit.it_interval.tv_usec =
1382 (IV)((interval - (NV)newit.it_interval.tv_sec) * NV_1E6);
1383 /* on some platforms the 1st arg to setitimer is an enum, which
1384 * causes -Wc++-compat to complain about passing an int instead
1386 GCC_DIAG_IGNORE_STMT(-Wc++-compat);
1387 if (setitimer(which, &newit, &oldit) == 0) {
1389 PUSHs(sv_2mortal(newSVnv(TV2NV(oldit.it_value))));
1390 if (GIMME == G_ARRAY) {
1392 PUSHs(sv_2mortal(newSVnv(TV2NV(oldit.it_interval))));
1395 GCC_DIAG_RESTORE_STMT;
1401 struct itimerval nowit;
1403 /* on some platforms the 1st arg to getitimer is an enum, which
1404 * causes -Wc++-compat to complain about passing an int instead
1406 GCC_DIAG_IGNORE_STMT(-Wc++-compat);
1407 if (getitimer(which, &nowit) == 0) {
1409 PUSHs(sv_2mortal(newSVnv(TV2NV(nowit.it_value))));
1410 if (GIMME == G_ARRAY) {
1412 PUSHs(sv_2mortal(newSVnv(TV2NV(nowit.it_interval))));
1415 GCC_DIAG_RESTORE_STMT;
1417 #endif /* #if defined(HAS_GETITIMER) && defined(HAS_SETITIMER) */
1419 #if defined(TIME_HIRES_UTIME)
1422 utime(accessed, modified, ...)
1429 struct timespec utbuf[2];
1430 struct timespec *utbufp = utbuf;
1439 if ( accessed == &PL_sv_undef && modified == &PL_sv_undef )
1442 if (SvNV(accessed) < 0.0 || SvNV(modified) < 0.0)
1443 croak("Time::HiRes::utime(%" NVgf ", %" NVgf
1444 "): negative time not invented yet",
1445 SvNV(accessed), SvNV(modified));
1446 Zero(&utbuf, sizeof utbuf, char);
1448 utbuf[0].tv_sec = (Time_t)SvNV(accessed); /* time accessed */
1449 utbuf[0].tv_nsec = (long)(
1450 (SvNV(accessed) - (NV)utbuf[0].tv_sec)
1451 * NV_1E9 + (NV)0.5);
1453 utbuf[1].tv_sec = (Time_t)SvNV(modified); /* time modified */
1454 utbuf[1].tv_nsec = (long)(
1455 (SvNV(modified) - (NV)utbuf[1].tv_sec)
1456 * NV_1E9 + (NV)0.5);
1460 file = POPs; items--;
1462 if (SvROK(file) && GvIO(SvRV(file)) && IoIFP(sv_2io(SvRV(file)))) {
1463 int fd = PerlIO_fileno(IoIFP(sv_2io(file)));
1465 SETERRNO(EBADF,RMS_IFI);
1468 if (FUTIMENS_AVAILABLE) {
1469 if (futimens(fd, utbufp) == 0) {
1473 croak("futimens unimplemented in this platform");
1475 #else /* HAS_FUTIMENS */
1476 croak("futimens unimplemented in this platform");
1477 #endif /* HAS_FUTIMENS */
1481 #ifdef HAS_UTIMENSAT
1482 if (UTIMENSAT_AVAILABLE) {
1484 char * name = SvPV(file, len);
1485 if (IS_SAFE_PATHNAME(name, len, "utime") &&
1486 utimensat(AT_FDCWD, name, utbufp, 0) == 0) {
1490 croak("utimensat unimplemented in this platform");
1492 #else /* HAS_UTIMENSAT */
1493 croak("utimensat unimplemented in this platform");
1494 #endif /* HAS_UTIMENSAT */
1502 #else /* #if defined(TIME_HIRES_UTIME) */
1505 utime(accessed, modified, ...)
1507 croak("Time::HiRes::utime(): unimplemented in this platform");
1512 #endif /* #if defined(TIME_HIRES_UTIME) */
1514 #if defined(TIME_HIRES_CLOCK_GETTIME)
1517 clock_gettime(clock_id = CLOCK_REALTIME)
1523 #ifdef TIME_HIRES_CLOCK_GETTIME_SYSCALL
1524 status = syscall(SYS_clock_gettime, clock_id, &ts);
1526 status = clock_gettime(clock_id, &ts);
1528 RETVAL = status == 0 ? ts.tv_sec + (NV) ts.tv_nsec / NV_1E9 : -1;
1533 #else /* if defined(TIME_HIRES_CLOCK_GETTIME) */
1536 clock_gettime(clock_id = 0)
1539 PERL_UNUSED_ARG(clock_id);
1540 croak("Time::HiRes::clock_gettime(): unimplemented in this platform");
1545 #endif /* #if defined(TIME_HIRES_CLOCK_GETTIME) */
1547 #if defined(TIME_HIRES_CLOCK_GETRES)
1550 clock_getres(clock_id = CLOCK_REALTIME)
1556 #ifdef TIME_HIRES_CLOCK_GETRES_SYSCALL
1557 status = syscall(SYS_clock_getres, clock_id, &ts);
1559 status = clock_getres(clock_id, &ts);
1561 RETVAL = status == 0 ? ts.tv_sec + (NV) ts.tv_nsec / NV_1E9 : -1;
1566 #else /* if defined(TIME_HIRES_CLOCK_GETRES) */
1569 clock_getres(clock_id = 0)
1572 PERL_UNUSED_ARG(clock_id);
1573 croak("Time::HiRes::clock_getres(): unimplemented in this platform");
1578 #endif /* #if defined(TIME_HIRES_CLOCK_GETRES) */
1580 #if defined(TIME_HIRES_CLOCK_NANOSLEEP) && defined(TIMER_ABSTIME)
1583 clock_nanosleep(clock_id, nsec, flags = 0)
1588 struct timespec sleepfor, unslept;
1591 croak("Time::HiRes::clock_nanosleep(..., %" NVgf
1592 "): negative time not invented yet", nsec);
1593 nanosleep_init(nsec, &sleepfor, &unslept);
1594 if (clock_nanosleep(clock_id, flags, &sleepfor, &unslept) == 0) {
1597 RETVAL = nsec_without_unslept(&sleepfor, &unslept);
1602 #else /* if defined(TIME_HIRES_CLOCK_NANOSLEEP) && defined(TIMER_ABSTIME) */
1605 clock_nanosleep(clock_id, nsec, flags = 0)
1610 PERL_UNUSED_ARG(clock_id);
1611 PERL_UNUSED_ARG(nsec);
1612 PERL_UNUSED_ARG(flags);
1613 croak("Time::HiRes::clock_nanosleep(): unimplemented in this platform");
1618 #endif /* #if defined(TIME_HIRES_CLOCK_NANOSLEEP) && defined(TIMER_ABSTIME) */
1620 #if defined(TIME_HIRES_CLOCK) && defined(CLOCKS_PER_SEC)
1628 RETVAL = clocks == (clock_t) -1 ? (clock_t) -1 : (NV)clocks / (NV)CLOCKS_PER_SEC;
1633 #else /* if defined(TIME_HIRES_CLOCK) && defined(CLOCKS_PER_SEC) */
1638 croak("Time::HiRes::clock(): unimplemented in this platform");
1643 #endif /* #if defined(TIME_HIRES_CLOCK) && defined(CLOCKS_PER_SEC) */
1652 Time::HiRes::lstat = 1
1654 XPUSHs(sv_2mortal(newSVsv(items == 1 ? ST(0) : DEFSV)));
1657 PL_laststatval = -1;
1659 Zero(&fakeop, 1, OP);
1660 fakeop.op_type = ix ? OP_LSTAT : OP_STAT;
1661 fakeop.op_ppaddr = PL_ppaddr[fakeop.op_type];
1662 fakeop.op_flags = GIMME_V == G_ARRAY ? OPf_WANT_LIST :
1663 GIMME_V == G_SCALAR ? OPf_WANT_SCALAR : OPf_WANT_VOID;
1665 (void)fakeop.op_ppaddr(aTHX);
1668 nret = SP+1 - &ST(0);
1670 UV atime = SvUV(ST( 8));
1671 UV mtime = SvUV(ST( 9));
1672 UV ctime = SvUV(ST(10));
1676 hrstatns(&atime_nsec, &mtime_nsec, &ctime_nsec);
1678 ST( 8) = sv_2mortal(newSVnv(atime + (NV) atime_nsec / NV_1E9));
1680 ST( 9) = sv_2mortal(newSVnv(mtime + (NV) mtime_nsec / NV_1E9));
1682 ST(10) = sv_2mortal(newSVnv(ctime + (NV) ctime_nsec / NV_1E9));