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 #if PERL_VERSION_GE(5,7,3) && !PERL_VERSION_GE(5,10,1)
62 # define SAVEOP() SAVEVPTR(PL_op)
65 #define IV_1E6 1000000
66 #define IV_1E7 10000000
67 #define IV_1E9 1000000000
69 #define NV_1E6 1000000.0
70 #define NV_1E7 10000000.0
71 #define NV_1E9 1000000000.0
73 #ifndef PerlProc_pause
74 # define PerlProc_pause() Pause()
80 # undef Pause /* In case perl.h did it already. */
81 # define Pause() sleep(~0) /* Zzz for a long time. */
84 /* Though the cpp define ITIMER_VIRTUAL is available the functionality
85 * is not supported in Cygwin as of August 2004, ditto for Win32.
86 * Neither are ITIMER_PROF or ITIMER_REALPROF implemented. --jhi
88 #if defined(__CYGWIN__) || defined(WIN32)
89 # undef ITIMER_VIRTUAL
91 # undef ITIMER_REALPROF
94 #ifndef TIME_HIRES_CLOCKID_T
95 typedef int clockid_t;
98 #if defined(TIME_HIRES_CLOCK_GETTIME) && defined(_STRUCT_ITIMERSPEC)
100 /* HP-UX has CLOCK_XXX values but as enums, not as defines.
101 * The only way to detect these would be to test compile for each. */
103 /* However, it seems that at least in HP-UX 11.31 ia64 there *are*
104 * defines for these, so let's try detecting them. */
105 # ifndef CLOCK_REALTIME
106 # define CLOCK_REALTIME CLOCK_REALTIME
107 # define CLOCK_VIRTUAL CLOCK_VIRTUAL
108 # define CLOCK_PROFILE CLOCK_PROFILE
110 # endif /* # ifdef __hpux */
112 #endif /* #if defined(TIME_HIRES_CLOCK_GETTIME) && defined(_STRUCT_ITIMERSPEC) */
114 #if defined(WIN32) || defined(CYGWIN_WITH_W32API)
116 # ifndef HAS_GETTIMEOFDAY
117 # define HAS_GETTIMEOFDAY
120 /* shows up in winsock.h?
128 unsigned __int64 ft_i64;
132 # define MY_CXT_KEY "Time::HiRes_" XS_VERSION
135 unsigned long run_count;
136 unsigned __int64 base_ticks;
137 unsigned __int64 tick_frequency;
138 FT_t base_systime_as_filetime;
139 unsigned __int64 reset_time;
144 /* Number of 100 nanosecond units from 1/1/1601 to 1/1/1970 */
146 # define Const64(x) x##LL
148 # define Const64(x) x##i64
150 # define EPOCH_BIAS Const64(116444736000000000)
154 # define IV_1E6LL 1000000LL /* Needed because of Const64() ##-appends LL (or i64). */
155 # define IV_1E7LL 10000000LL
156 # define IV_1E9LL 1000000000LL
158 # define IV_1E6i64 1000000i64
159 # define IV_1E7i64 10000000i64
160 # define IV_1E9i64 1000000000i64
164 /* NOTE: This does not compute the timezone info (doing so can be expensive,
165 * and appears to be unsupported even by glibc) */
167 /* dMY_CXT needs a Perl context and we don't want to call PERL_GET_CONTEXT
168 for performance reasons */
171 # define gettimeofday(tp, not_used) _gettimeofday(aTHX_ tp, not_used)
173 /* If the performance counter delta drifts more than 0.5 seconds from the
174 * system time then we recalibrate to the system time. This means we may
175 * move *backwards* in time! */
176 # define MAX_PERF_COUNTER_SKEW Const64(5000000) /* 0.5 seconds */
178 /* Reset reading from the performance counter every five minutes.
179 * Many PC clocks just seem to be so bad. */
180 # define MAX_PERF_COUNTER_TICKS Const64(300000000) /* 300 seconds */
183 _gettimeofday(pTHX_ struct timeval *tp, void *not_used)
187 unsigned __int64 ticks;
190 PERL_UNUSED_ARG(not_used);
191 if (MY_CXT.run_count++ == 0 ||
192 MY_CXT.base_systime_as_filetime.ft_i64 > MY_CXT.reset_time) {
194 QueryPerformanceFrequency((LARGE_INTEGER*)&MY_CXT.tick_frequency);
195 QueryPerformanceCounter((LARGE_INTEGER*)&MY_CXT.base_ticks);
196 GetSystemTimeAsFileTime(&MY_CXT.base_systime_as_filetime.ft_val);
197 ft.ft_i64 = MY_CXT.base_systime_as_filetime.ft_i64;
198 MY_CXT.reset_time = ft.ft_i64 + MAX_PERF_COUNTER_TICKS;
202 QueryPerformanceCounter((LARGE_INTEGER*)&ticks);
203 ticks -= MY_CXT.base_ticks;
204 ft.ft_i64 = MY_CXT.base_systime_as_filetime.ft_i64
205 + Const64(IV_1E7) * (ticks / MY_CXT.tick_frequency)
206 +(Const64(IV_1E7) * (ticks % MY_CXT.tick_frequency)) / MY_CXT.tick_frequency;
207 diff = ft.ft_i64 - MY_CXT.base_systime_as_filetime.ft_i64;
208 if (diff < -MAX_PERF_COUNTER_SKEW || diff > MAX_PERF_COUNTER_SKEW) {
209 MY_CXT.base_ticks += ticks;
210 GetSystemTimeAsFileTime(&MY_CXT.base_systime_as_filetime.ft_val);
211 ft.ft_i64 = MY_CXT.base_systime_as_filetime.ft_i64;
215 /* seconds since epoch */
216 tp->tv_sec = (long)((ft.ft_i64 - EPOCH_BIAS) / Const64(IV_1E7));
218 /* microseconds remaining */
219 tp->tv_usec = (long)((ft.ft_i64 / Const64(10)) % Const64(IV_1E6));
223 #endif /* #if defined(WIN32) || defined(CYGWIN_WITH_W32API) */
225 #if !defined(HAS_GETTIMEOFDAY) && defined(VMS)
226 # define HAS_GETTIMEOFDAY
229 # include <time.h> /* gettimeofday */
230 # include <stdlib.h> /* qdiv */
231 # include <starlet.h> /* sys$gettim */
232 # include <descrip.h>
234 # include <lib$routines.h> /* lib$ediv() */
238 VMS binary time is expressed in 100 nano-seconds since
239 system base time which is 17-NOV-1858 00:00:00.00
242 # define DIV_100NS_TO_SECS 10000000L
243 # define DIV_100NS_TO_USECS 10L
246 gettimeofday is supposed to return times since the epoch
247 so need to determine this in terms of VMS base time
249 static $DESCRIPTOR(dscepoch,"01-JAN-1970 00:00:00.00");
252 static long base_adjust[2]={0L,0L};
254 static __int64 base_adjust=0;
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
264 /* method used to handle UTC conversions:
265 * 1 == CRTL gmtime(); 2 == SYS$TIMEZONE_DIFFERENTIAL; 3 == no correction
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 };
274 static time_t toutc_dst(time_t loc) {
277 if ((rsltmp = localtime(&loc)) == NULL) return -1;
278 loc -= utc_offset_secs;
279 if (rsltmp->tm_isdst) loc -= 3600;
283 static time_t toloc_dst(time_t utc) {
286 utc += utc_offset_secs;
287 if ((rsltmp = localtime(&utc)) == NULL) return -1;
288 if (rsltmp->tm_isdst) utc += 3600;
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))))
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))))
307 if (gmtime_emulation_type == 0) {
309 time_t base = 15 * 86400; /* 15jan71; to avoid month/year ends between */
310 /* results of calls to gmtime() and localtime() */
313 gmtime_emulation_type++;
314 if ((tm_p = gmtime(&base)) == NULL) { /* CRTL gmtime() is a fake */
315 char off[LNM$C_NAMLENGTH+1];;
317 gmtime_emulation_type++;
318 if (!Perl_vmstrnenv("SYS$TIMEZONE_DIFFERENTIAL",off,0,fildev,0)) {
319 gmtime_emulation_type++;
321 Perl_warn(aTHX_ "no UTC offset information; assuming local time is UTC");
323 else { utc_offset_secs = atol(off); }
325 else { /* We've got a working gmtime() */
326 struct tm gmt, local;
329 tm_p = localtime(&base);
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);
342 gettimeofday (struct timeval *tp, void *tpz)
348 long div_100ns_to_secs;
349 long div_100ns_to_usecs;
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.
365 if (base_adjust[0]==0 && base_adjust[1]==0) {
367 if (base_adjust==0) { /* Need to determine epoch adjustment */
369 ret=sys$bintim(&dscepoch,&base_adjust);
370 if (1 != (ret &&1)) {
376 ret=sys$gettim(&quad); /* Get VMS system time */
377 if ((1 && ret) == 1) {
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);
386 lib$ediv(&div_100ns_to_usecs,&quad1,&quo1,&rem1);
387 tp->tv_sec = quo; /* Whole seconds */
388 tp->tv_usec = quo1; /* Micro-seconds */
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 */
402 if (VMSISH_TIME) tp->tv_sec = _toloc(tp->tv_sec);
404 if (!VMSISH_TIME) tp->tv_sec = _toutc(tp->tv_sec);
409 #endif /* #if !defined(HAS_GETTIMEOFDAY) && defined(VMS) */
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)
419 # define usleep hrt_usleep /* could conflict with ncurses for static build */
422 hrt_usleep(unsigned long usec) /* This is used to emulate usleep. */
425 res.tv_sec = usec / IV_1E6;
426 res.tv_nsec = ( usec - res.tv_sec * IV_1E6 ) * 1000;
427 nanosleep(&res, NULL);
430 #endif /* #if !defined(HAS_USLEEP) && defined(TIME_HIRES_NANOSLEEP) */
432 #if !defined(HAS_USLEEP) && defined(HAS_SELECT)
433 # ifndef SELECT_IS_BROKEN
435 # define usleep hrt_usleep /* could conflict with ncurses for static build */
438 hrt_usleep(unsigned long usec)
443 select(0, (Select_fd_set_t)NULL, (Select_fd_set_t)NULL,
444 (Select_fd_set_t)NULL, &tv);
447 #endif /* #if !defined(HAS_USLEEP) && defined(HAS_SELECT) */
449 #if !defined(HAS_USLEEP) && defined(WIN32)
451 # define usleep hrt_usleep /* could conflict with ncurses for static build */
454 hrt_usleep(unsigned long usec)
460 #endif /* #if !defined(HAS_USLEEP) && defined(WIN32) */
462 #if !defined(HAS_USLEEP) && defined(HAS_POLL)
464 # define usleep hrt_usleep /* could conflict with ncurses for static build */
467 hrt_usleep(unsigned long usec)
469 int msec = usec / 1000;
473 #endif /* #if !defined(HAS_USLEEP) && defined(HAS_POLL) */
475 #if defined(HAS_SETITIMER) && defined(ITIMER_REAL)
478 hrt_ualarm_itimero(struct itimerval *oitv, int usec, int uinterval)
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);
488 #endif /* #if !defined(HAS_UALARM) && defined(HAS_SETITIMER) */
490 #if !defined(HAS_UALARM) && defined(HAS_SETITIMER)
492 # define ualarm hrt_ualarm_itimer /* could conflict with ncurses for static build */
495 #if !defined(HAS_UALARM) && defined(VMS)
497 # define ualarm vms_ualarm
499 # include <lib$routines.h>
501 # include <starlet.h>
502 # include <descrip.h>
507 # define VMSERR(s) (!((s)&1))
510 us_to_VMS(useconds_t mseconds, unsigned long v[])
519 iss = lib$addx(qq,qq,qq);
520 if (VMSERR(iss)) lib$signal(iss);
521 iss = lib$subx(v,qq,v);
522 if (VMSERR(iss)) lib$signal(iss);
523 iss = lib$addx(qq,qq,qq);
524 if (VMSERR(iss)) lib$signal(iss);
525 iss = lib$subx(v,qq,v);
526 if (VMSERR(iss)) lib$signal(iss);
527 iss = lib$subx(v,qq,v);
528 if (VMSERR(iss)) lib$signal(iss);
532 VMS_to_us(unsigned long v[])
535 unsigned long div=10,quot, rem;
537 iss = lib$ediv(&div,v,",&rem);
538 if (VMSERR(iss)) lib$signal(iss);
543 typedef unsigned short word;
544 typedef struct _ualarm {
547 unsigned long delay[2];
548 unsigned long interval[2];
549 unsigned long remain[2];
554 static Alarm *a0, alarm_base;
558 # define UAL_ACTIVE 4
559 static void ualarm_AST(Alarm *a);
562 vms_ualarm(int mseconds, int interval)
571 static struct item_list3 itmlst[2];
572 static int first = 1;
578 itmlst[0].code = JPI$_ASTEN;
579 itmlst[0].length = sizeof(asten);
580 itmlst[0].retlenaddr = NULL;
582 itmlst[1].length = 0;
583 itmlst[1].bufaddr = NULL;
584 itmlst[1].retlenaddr = NULL;
586 iss = lib$get_ef(&alarm_ef);
587 if (VMSERR(iss)) lib$signal(iss);
590 a0->function = UAL_NULL;
592 itmlst[0].bufaddr = &asten;
594 iss = sys$getjpiw(0,0,0,itmlst,0,0,0);
595 if (VMSERR(iss)) lib$signal(iss);
596 if (!(asten&0x08)) return -1;
600 a->function = UAL_SET;
602 a->function = UAL_CLEAR;
605 us_to_VMS(mseconds, a->delay);
607 us_to_VMS(interval, a->interval);
612 iss = sys$clref(alarm_ef);
613 if (VMSERR(iss)) lib$signal(iss);
615 iss = sys$dclast(ualarm_AST,a,0);
616 if (VMSERR(iss)) lib$signal(iss);
618 iss = sys$waitfr(alarm_ef);
619 if (VMSERR(iss)) lib$signal(iss);
621 if (a->function == UAL_ACTIVE)
622 return VMS_to_us(a->remain);
633 unsigned long now[2];
635 iss = sys$gettim(now);
636 if (VMSERR(iss)) lib$signal(iss);
638 if (a->function == UAL_SET || a->function == UAL_CLEAR) {
639 if (a0->function == UAL_ACTIVE) {
640 iss = sys$cantim(a0,PSL$C_USER);
641 if (VMSERR(iss)) lib$signal(iss);
643 iss = lib$subx(a0->remain, now, a->remain);
644 if (VMSERR(iss)) lib$signal(iss);
646 if (a->remain[1] & 0x80000000)
647 a->remain[0] = a->remain[1] = 0;
650 if (a->function == UAL_SET) {
651 a->function = a0->function;
652 a0->function = UAL_ACTIVE;
653 a0->repeat = a->repeat;
655 a0->interval[0] = a->interval[0];
656 a0->interval[1] = a->interval[1];
658 a0->delay[0] = a->delay[0];
659 a0->delay[1] = a->delay[1];
661 iss = lib$subx(now, a0->delay, a0->remain);
662 if (VMSERR(iss)) lib$signal(iss);
664 iss = sys$setimr(0,a0->delay,ualarm_AST,a0);
665 if (VMSERR(iss)) lib$signal(iss);
667 a->function = a0->function;
668 a0->function = UAL_NULL;
670 iss = sys$setef(alarm_ef);
671 if (VMSERR(iss)) lib$signal(iss);
672 } else if (a->function == UAL_ACTIVE) {
674 iss = lib$subx(now, a->interval, a->remain);
675 if (VMSERR(iss)) lib$signal(iss);
677 iss = sys$setimr(0,a->interval,ualarm_AST,a);
678 if (VMSERR(iss)) lib$signal(iss);
680 a->function = UAL_NULL;
683 if (VMSERR(iss)) lib$signal(iss);
684 lib$signal(SS$_ASTFLT);
686 lib$signal(SS$_BADPARAM);
690 #endif /* #if !defined(HAS_UALARM) && defined(VMS) */
692 #ifdef HAS_GETTIMEOFDAY
695 myU2time(pTHX_ UV *ret)
699 status = gettimeofday (&Tp, NULL);
713 status = gettimeofday (&Tp, NULL);
714 return status == 0 ? Tp.tv_sec + (Tp.tv_usec / NV_1E6) : -1.0;
717 #endif /* #ifdef HAS_GETTIMEOFDAY */
720 hrstatns(UV *atime_nsec, UV *mtime_nsec, UV *ctime_nsec)
723 #if TIME_HIRES_STAT == 1
724 *atime_nsec = PL_statcache.st_atimespec.tv_nsec;
725 *mtime_nsec = PL_statcache.st_mtimespec.tv_nsec;
726 *ctime_nsec = PL_statcache.st_ctimespec.tv_nsec;
727 #elif TIME_HIRES_STAT == 2
728 *atime_nsec = PL_statcache.st_atimensec;
729 *mtime_nsec = PL_statcache.st_mtimensec;
730 *ctime_nsec = PL_statcache.st_ctimensec;
731 #elif TIME_HIRES_STAT == 3
732 *atime_nsec = PL_statcache.st_atime_n;
733 *mtime_nsec = PL_statcache.st_mtime_n;
734 *ctime_nsec = PL_statcache.st_ctime_n;
735 #elif TIME_HIRES_STAT == 4
736 *atime_nsec = PL_statcache.st_atim.tv_nsec;
737 *mtime_nsec = PL_statcache.st_mtim.tv_nsec;
738 *ctime_nsec = PL_statcache.st_ctim.tv_nsec;
739 #elif TIME_HIRES_STAT == 5
740 *atime_nsec = PL_statcache.st_uatime * 1000;
741 *mtime_nsec = PL_statcache.st_umtime * 1000;
742 *ctime_nsec = PL_statcache.st_uctime * 1000;
743 #else /* !TIME_HIRES_STAT */
747 #endif /* !TIME_HIRES_STAT */
750 /* Until Apple implements clock_gettime()
751 * (ditto clock_getres() and clock_nanosleep())
752 * we will emulate them using the Mach kernel interfaces. */
753 #if defined(PERL_DARWIN) && \
754 (defined(TIME_HIRES_CLOCK_GETTIME_EMULATION) || \
755 defined(TIME_HIRES_CLOCK_GETRES_EMULATION) || \
756 defined(TIME_HIRES_CLOCK_NANOSLEEP_EMULATION))
758 # ifndef CLOCK_REALTIME
759 # define CLOCK_REALTIME 0x01
760 # define CLOCK_MONOTONIC 0x02
763 # ifndef TIMER_ABSTIME
764 # define TIMER_ABSTIME 0x01
768 # define PERL_DARWIN_MUTEX
771 # ifdef PERL_DARWIN_MUTEX
772 STATIC perl_mutex darwin_time_mutex;
775 # include <mach/mach_time.h>
777 static uint64_t absolute_time_init;
778 static mach_timebase_info_data_t timebase_info;
779 static struct timespec timespec_init;
781 static int darwin_time_init() {
784 # ifdef PERL_DARWIN_MUTEX
785 MUTEX_LOCK(&darwin_time_mutex);
787 if (absolute_time_init == 0) {
788 /* mach_absolute_time() cannot fail */
789 absolute_time_init = mach_absolute_time();
790 success = mach_timebase_info(&timebase_info) == KERN_SUCCESS;
792 success = gettimeofday(&tv, NULL) == 0;
794 timespec_init.tv_sec = tv.tv_sec;
795 timespec_init.tv_nsec = tv.tv_usec * 1000;
799 # ifdef PERL_DARWIN_MUTEX
800 MUTEX_UNLOCK(&darwin_time_mutex);
805 # ifdef TIME_HIRES_CLOCK_GETTIME_EMULATION
806 static int th_clock_gettime(clockid_t clock_id, struct timespec *ts) {
807 if (darwin_time_init() && timebase_info.denom) {
812 ((mach_absolute_time() - absolute_time_init) *
813 (uint64_t)timebase_info.numer) / (uint64_t)timebase_info.denom;
814 ts->tv_sec = timespec_init.tv_sec + nanos / IV_1E9;
815 ts->tv_nsec = timespec_init.tv_nsec + nanos % IV_1E9;
819 case CLOCK_MONOTONIC:
822 (mach_absolute_time() *
823 (uint64_t)timebase_info.numer) / (uint64_t)timebase_info.denom;
824 ts->tv_sec = nanos / IV_1E9;
825 ts->tv_nsec = nanos - ts->tv_sec * IV_1E9;
834 SETERRNO(EINVAL, LIB_INVARG);
838 # define clock_gettime(clock_id, ts) th_clock_gettime((clock_id), (ts))
840 # endif /* TIME_HIRES_CLOCK_GETTIME_EMULATION */
842 # ifdef TIME_HIRES_CLOCK_GETRES_EMULATION
843 static int th_clock_getres(clockid_t clock_id, struct timespec *ts) {
844 if (darwin_time_init() && timebase_info.denom) {
847 case CLOCK_MONOTONIC:
849 /* In newer kernels both the numer and denom are one,
850 * resulting in conversion factor of one, which is of
851 * course unrealistic. */
852 ts->tv_nsec = timebase_info.numer / timebase_info.denom;
859 SETERRNO(EINVAL, LIB_INVARG);
863 # define clock_getres(clock_id, ts) th_clock_getres((clock_id), (ts))
864 # endif /* TIME_HIRES_CLOCK_GETRES_EMULATION */
866 # ifdef TIME_HIRES_CLOCK_NANOSLEEP_EMULATION
867 static int th_clock_nanosleep(clockid_t clock_id, int flags,
868 const struct timespec *rqtp,
869 struct timespec *rmtp) {
870 if (darwin_time_init()) {
873 case CLOCK_MONOTONIC:
875 uint64_t nanos = rqtp->tv_sec * IV_1E9 + rqtp->tv_nsec;
877 if ((flags & TIMER_ABSTIME)) {
879 timespec_init.tv_sec * IV_1E9 + timespec_init.tv_nsec;
880 nanos = nanos > back ? nanos - back : 0;
883 mach_wait_until(mach_absolute_time() + nanos) == KERN_SUCCESS;
885 /* In the relative sleep, the rmtp should be filled in with
886 * the 'unused' part of the rqtp in case the sleep gets
887 * interrupted by a signal. But it is unknown how signals
888 * interact with mach_wait_until(). In the absolute sleep,
889 * the rmtp should stay untouched. */
901 SETERRNO(EINVAL, LIB_INVARG);
905 # define clock_nanosleep(clock_id, flags, rqtp, rmtp) \
906 th_clock_nanosleep((clock_id), (flags), (rqtp), (rmtp))
908 # endif /* TIME_HIRES_CLOCK_NANOSLEEP_EMULATION */
910 #endif /* PERL_DARWIN */
912 /* The macOS headers warn about using certain interfaces in
913 * OS-release-ignorant manner, for example:
915 * warning: 'futimens' is only available on macOS 10.13 or newer
916 * [-Wunguarded-availability-new]
918 * (ditto for utimensat)
920 * There is clang __builtin_available() *runtime* check for this.
921 * The gotchas are that neither __builtin_available() nor __has_builtin()
922 * are always available.
924 #ifndef __has_builtin
925 # define __has_builtin(x) 0 /* non-clang */
928 # if defined(PERL_DARWIN) && __has_builtin(__builtin_available)
929 # define FUTIMENS_AVAILABLE __builtin_available(macOS 10.13, *)
931 # define FUTIMENS_AVAILABLE 1
934 # define FUTIMENS_AVAILABLE 0
937 # if defined(PERL_DARWIN) && __has_builtin(__builtin_available)
938 # define UTIMENSAT_AVAILABLE __builtin_available(macOS 10.13, *)
940 # define UTIMENSAT_AVAILABLE 1
943 # define UTIMENSAT_AVAILABLE 0
946 #include "const-c.inc"
948 #if (defined(TIME_HIRES_NANOSLEEP)) || \
949 (defined(TIME_HIRES_CLOCK_NANOSLEEP) && defined(TIMER_ABSTIME))
952 nanosleep_init(NV nsec,
953 struct timespec *sleepfor,
954 struct timespec *unslept) {
955 sleepfor->tv_sec = (Time_t)(nsec / NV_1E9);
956 sleepfor->tv_nsec = (long)(nsec - ((NV)sleepfor->tv_sec) * NV_1E9);
958 unslept->tv_nsec = 0;
962 nsec_without_unslept(struct timespec *sleepfor,
963 const struct timespec *unslept) {
964 if (sleepfor->tv_sec >= unslept->tv_sec) {
965 sleepfor->tv_sec -= unslept->tv_sec;
966 if (sleepfor->tv_nsec >= unslept->tv_nsec) {
967 sleepfor->tv_nsec -= unslept->tv_nsec;
968 } else if (sleepfor->tv_sec > 0) {
970 sleepfor->tv_nsec += IV_1E9;
971 sleepfor->tv_nsec -= unslept->tv_nsec;
973 sleepfor->tv_sec = 0;
974 sleepfor->tv_nsec = 0;
977 sleepfor->tv_sec = 0;
978 sleepfor->tv_nsec = 0;
980 return ((NV)sleepfor->tv_sec) * NV_1E9 + ((NV)sleepfor->tv_nsec);
985 /* In case Perl and/or Devel::PPPort are too old, minimally emulate
986 * IS_SAFE_PATHNAME() (which looks for zero bytes in the pathname). */
987 #ifndef IS_SAFE_PATHNAME
988 # if PERL_VERSION >= 12 /* Perl_ck_warner is 5.10.0 -> */
989 # ifdef WARN_SYSCALLS
990 # define WARNEMUCAT WARN_SYSCALLS /* 5.22.0 -> */
992 # define WARNEMUCAT WARN_MISC
994 # define WARNEMU(opname) Perl_ck_warner(aTHX_ packWARN(WARNEMUCAT), "Invalid \\0 character in pathname for %s",opname)
996 # define WARNEMU(opname) Perl_warn(aTHX_ "Invalid \\0 character in pathname for %s",opname)
998 # define IS_SAFE_PATHNAME(pv, len, opname) (((len)>1)&&memchr((pv), 0, (len)-1)?(SETERRNO(ENOENT, LIB_INVARG),WARNEMU(opname),FALSE):(TRUE))
1001 MODULE = Time::HiRes PACKAGE = Time::HiRes
1010 #ifdef HAS_GETTIMEOFDAY
1012 (void) hv_store(PL_modglobal, "Time::NVtime", 12,
1013 newSViv(PTR2IV(myNVtime)), 0);
1014 (void) hv_store(PL_modglobal, "Time::U2time", 12,
1015 newSViv(PTR2IV(myU2time)), 0);
1018 #if defined(PERL_DARWIN)
1019 # if defined(USE_ITHREADS) && defined(PERL_DARWIN_MUTEX)
1020 MUTEX_INIT(&darwin_time_mutex);
1025 #if defined(USE_ITHREADS) && defined(MY_CXT_KEY)
1034 INCLUDE: const-xs.inc
1036 #if defined(HAS_USLEEP) && defined(HAS_GETTIMEOFDAY)
1042 struct timeval Ta, Tb;
1044 gettimeofday(&Ta, NULL);
1046 if (useconds >= NV_1E6) {
1047 IV seconds = (IV) (useconds / NV_1E6);
1048 /* If usleep() has been implemented using setitimer()
1049 * then this contortion is unnecessary-- but usleep()
1050 * may be implemented in some other way, so let's contort. */
1053 useconds -= NV_1E6 * seconds;
1055 } else if (useconds < 0.0)
1056 croak("Time::HiRes::usleep(%" NVgf
1057 "): negative time not invented yet", useconds);
1059 usleep((U32)useconds);
1063 gettimeofday(&Tb, NULL);
1065 printf("[%ld %ld] [%ld %ld]\n", Tb.tv_sec, Tb.tv_usec, Ta.tv_sec, Ta.tv_usec);
1067 RETVAL = NV_1E6*(Tb.tv_sec-Ta.tv_sec)+(NV)((IV)Tb.tv_usec-(IV)Ta.tv_usec);
1072 # if defined(TIME_HIRES_NANOSLEEP)
1078 struct timespec sleepfor, unslept;
1081 croak("Time::HiRes::nanosleep(%" NVgf
1082 "): negative time not invented yet", nsec);
1083 nanosleep_init(nsec, &sleepfor, &unslept);
1084 if (nanosleep(&sleepfor, &unslept) == 0) {
1087 RETVAL = nsec_without_unslept(&sleepfor, &unslept);
1092 # else /* #if defined(TIME_HIRES_NANOSLEEP) */
1098 PERL_UNUSED_ARG(nsec);
1099 croak("Time::HiRes::nanosleep(): unimplemented in this platform");
1104 # endif /* #if defined(TIME_HIRES_NANOSLEEP) */
1109 struct timeval Ta, Tb;
1111 gettimeofday(&Ta, NULL);
1113 NV seconds = SvNV(ST(0));
1114 if (seconds >= 0.0) {
1115 UV useconds = (UV)(1E6 * (seconds - (UV)seconds));
1117 sleep((U32)seconds);
1118 if ((IV)useconds < 0) {
1119 # if defined(__sparc64__) && defined(__GNUC__)
1120 /* Sparc64 gcc 2.95.3 (e.g. on NetBSD) has a bug
1121 * where (0.5 - (UV)(0.5)) will under certain
1122 * circumstances (if the double is cast to UV more
1123 * than once?) evaluate to -0.5, instead of 0.5. */
1124 useconds = -(IV)useconds;
1125 # endif /* #if defined(__sparc64__) && defined(__GNUC__) */
1126 if ((IV)useconds < 0)
1127 croak("Time::HiRes::sleep(%" NVgf
1128 "): internal error: useconds < 0 (unsigned %" UVuf
1129 " signed %" IVdf ")",
1130 seconds, useconds, (IV)useconds);
1134 croak("Time::HiRes::sleep(%" NVgf
1135 "): negative time not invented yet", seconds);
1139 gettimeofday(&Tb, NULL);
1141 printf("[%ld %ld] [%ld %ld]\n", Tb.tv_sec, Tb.tv_usec, Ta.tv_sec, Ta.tv_usec);
1143 RETVAL = (NV)(Tb.tv_sec-Ta.tv_sec)+0.000001*(NV)(Tb.tv_usec-Ta.tv_usec);
1148 #else /* #if defined(HAS_USLEEP) && defined(HAS_GETTIMEOFDAY) */
1154 PERL_UNUSED_ARG(useconds);
1155 croak("Time::HiRes::usleep(): unimplemented in this platform");
1160 #endif /* #if defined(HAS_USLEEP) && defined(HAS_GETTIMEOFDAY) */
1165 ualarm(useconds,uinterval=0)
1169 if (useconds < 0 || uinterval < 0)
1170 croak("Time::HiRes::ualarm(%d, %d): negative time not invented yet", useconds, uinterval);
1171 # if defined(HAS_SETITIMER) && defined(ITIMER_REAL)
1173 struct itimerval itv;
1174 if (hrt_ualarm_itimero(&itv, useconds, uinterval)) {
1175 /* To conform to ualarm's interface, we're actually ignoring
1179 RETVAL = itv.it_value.tv_sec * IV_1E6 + itv.it_value.tv_usec;
1183 if (useconds >= IV_1E6 || uinterval >= IV_1E6)
1184 croak("Time::HiRes::ualarm(%d, %d): useconds or uinterval"
1185 " equal to or more than %" IVdf,
1186 useconds, uinterval, IV_1E6);
1188 RETVAL = ualarm(useconds, uinterval);
1195 alarm(seconds,interval=0)
1199 if (seconds < 0.0 || interval < 0.0)
1200 croak("Time::HiRes::alarm(%" NVgf ", %" NVgf
1201 "): negative time not invented yet", seconds, interval);
1204 IV iseconds = (IV)seconds;
1205 IV iinterval = (IV)interval;
1206 NV fseconds = seconds - iseconds;
1207 NV finterval = interval - iinterval;
1208 IV useconds, uinterval;
1209 if (fseconds >= 1.0 || finterval >= 1.0)
1210 croak("Time::HiRes::alarm(%" NVgf ", %" NVgf
1211 "): seconds or interval too large to split correctly",
1214 useconds = IV_1E6 * fseconds;
1215 uinterval = IV_1E6 * finterval;
1216 # if defined(HAS_SETITIMER) && defined(ITIMER_REAL)
1218 struct itimerval nitv, oitv;
1219 nitv.it_value.tv_sec = iseconds;
1220 nitv.it_value.tv_usec = useconds;
1221 nitv.it_interval.tv_sec = iinterval;
1222 nitv.it_interval.tv_usec = uinterval;
1223 if (setitimer(ITIMER_REAL, &nitv, &oitv)) {
1224 /* To conform to alarm's interface, we're actually ignoring
1228 RETVAL = oitv.it_value.tv_sec + ((NV)oitv.it_value.tv_usec) / NV_1E6;
1232 if (iseconds || iinterval)
1233 croak("Time::HiRes::alarm(%" NVgf ", %" NVgf
1234 "): seconds or interval equal to or more than 1.0 ",
1237 RETVAL = (NV)ualarm( useconds, uinterval ) / NV_1E6;
1244 #else /* #ifdef HAS_UALARM */
1247 ualarm(useconds,interval=0)
1251 PERL_UNUSED_ARG(useconds);
1252 PERL_UNUSED_ARG(interval);
1253 croak("Time::HiRes::ualarm(): unimplemented in this platform");
1259 alarm(seconds,interval=0)
1263 PERL_UNUSED_ARG(seconds);
1264 PERL_UNUSED_ARG(interval);
1265 croak("Time::HiRes::alarm(): unimplemented in this platform");
1270 #endif /* #ifdef HAS_UALARM */
1272 #ifdef HAS_GETTIMEOFDAY
1280 status = gettimeofday (&Tp, NULL);
1282 if (GIMME == G_ARRAY) {
1284 PUSHs(sv_2mortal(newSViv(Tp.tv_sec)));
1285 PUSHs(sv_2mortal(newSViv(Tp.tv_usec)));
1288 PUSHs(sv_2mortal(newSVnv(Tp.tv_sec + (Tp.tv_usec / NV_1E6))));
1298 status = gettimeofday (&Tp, NULL);
1300 RETVAL = Tp.tv_sec + (Tp.tv_usec / NV_1E6);
1307 #endif /* #ifdef HAS_GETTIMEOFDAY */
1309 #if defined(HAS_GETITIMER) && defined(HAS_SETITIMER)
1311 # define TV2NV(tv) ((NV)((tv).tv_sec) + 0.000001 * (NV)((tv).tv_usec))
1314 setitimer(which, seconds, interval = 0)
1319 struct itimerval newit;
1320 struct itimerval oldit;
1322 if (seconds < 0.0 || interval < 0.0)
1323 croak("Time::HiRes::setitimer(%" IVdf ", %" NVgf ", %" NVgf
1324 "): negative time not invented yet",
1325 (IV)which, seconds, interval);
1326 newit.it_value.tv_sec = (IV)seconds;
1327 newit.it_value.tv_usec =
1328 (IV)((seconds - (NV)newit.it_value.tv_sec) * NV_1E6);
1329 newit.it_interval.tv_sec = (IV)interval;
1330 newit.it_interval.tv_usec =
1331 (IV)((interval - (NV)newit.it_interval.tv_sec) * NV_1E6);
1332 /* on some platforms the 1st arg to setitimer is an enum, which
1333 * causes -Wc++-compat to complain about passing an int instead
1335 GCC_DIAG_IGNORE_STMT(-Wc++-compat);
1336 if (setitimer(which, &newit, &oldit) == 0) {
1338 PUSHs(sv_2mortal(newSVnv(TV2NV(oldit.it_value))));
1339 if (GIMME == G_ARRAY) {
1341 PUSHs(sv_2mortal(newSVnv(TV2NV(oldit.it_interval))));
1344 GCC_DIAG_RESTORE_STMT;
1350 struct itimerval nowit;
1352 /* on some platforms the 1st arg to getitimer is an enum, which
1353 * causes -Wc++-compat to complain about passing an int instead
1355 GCC_DIAG_IGNORE_STMT(-Wc++-compat);
1356 if (getitimer(which, &nowit) == 0) {
1358 PUSHs(sv_2mortal(newSVnv(TV2NV(nowit.it_value))));
1359 if (GIMME == G_ARRAY) {
1361 PUSHs(sv_2mortal(newSVnv(TV2NV(nowit.it_interval))));
1364 GCC_DIAG_RESTORE_STMT;
1366 #endif /* #if defined(HAS_GETITIMER) && defined(HAS_SETITIMER) */
1368 #if defined(TIME_HIRES_UTIME)
1371 utime(accessed, modified, ...)
1378 struct timespec utbuf[2];
1379 struct timespec *utbufp = utbuf;
1388 if ( accessed == &PL_sv_undef && modified == &PL_sv_undef )
1391 if (SvNV(accessed) < 0.0 || SvNV(modified) < 0.0)
1392 croak("Time::HiRes::utime(%" NVgf ", %" NVgf
1393 "): negative time not invented yet",
1394 SvNV(accessed), SvNV(modified));
1395 Zero(&utbuf, sizeof utbuf, char);
1397 utbuf[0].tv_sec = (Time_t)SvNV(accessed); /* time accessed */
1398 utbuf[0].tv_nsec = (long)(
1399 (SvNV(accessed) - (NV)utbuf[0].tv_sec)
1400 * NV_1E9 + (NV)0.5);
1402 utbuf[1].tv_sec = (Time_t)SvNV(modified); /* time modified */
1403 utbuf[1].tv_nsec = (long)(
1404 (SvNV(modified) - (NV)utbuf[1].tv_sec)
1405 * NV_1E9 + (NV)0.5);
1409 file = POPs; items--;
1411 if (SvROK(file) && GvIO(SvRV(file)) && IoIFP(sv_2io(SvRV(file)))) {
1412 int fd = PerlIO_fileno(IoIFP(sv_2io(file)));
1414 SETERRNO(EBADF,RMS_IFI);
1416 # ifdef HAS_FUTIMENS
1417 if (FUTIMENS_AVAILABLE) {
1418 if (futimens(fd, utbufp) == 0) {
1422 croak("futimens unimplemented in this platform");
1424 # else /* HAS_FUTIMENS */
1425 croak("futimens unimplemented in this platform");
1426 # endif /* HAS_FUTIMENS */
1430 # ifdef HAS_UTIMENSAT
1431 if (UTIMENSAT_AVAILABLE) {
1433 char * name = SvPV(file, len);
1434 if (IS_SAFE_PATHNAME(name, len, "utime") &&
1435 utimensat(AT_FDCWD, name, utbufp, 0) == 0) {
1440 croak("utimensat unimplemented in this platform");
1442 # else /* HAS_UTIMENSAT */
1443 croak("utimensat unimplemented in this platform");
1444 # endif /* HAS_UTIMENSAT */
1452 #else /* #if defined(TIME_HIRES_UTIME) */
1455 utime(accessed, modified, ...)
1457 croak("Time::HiRes::utime(): unimplemented in this platform");
1462 #endif /* #if defined(TIME_HIRES_UTIME) */
1464 #if defined(TIME_HIRES_CLOCK_GETTIME)
1467 clock_gettime(clock_id = CLOCK_REALTIME)
1473 # ifdef TIME_HIRES_CLOCK_GETTIME_SYSCALL
1474 status = syscall(SYS_clock_gettime, clock_id, &ts);
1476 status = clock_gettime(clock_id, &ts);
1478 RETVAL = status == 0 ? ts.tv_sec + (NV) ts.tv_nsec / NV_1E9 : -1;
1483 #else /* if defined(TIME_HIRES_CLOCK_GETTIME) */
1486 clock_gettime(clock_id = 0)
1489 PERL_UNUSED_ARG(clock_id);
1490 croak("Time::HiRes::clock_gettime(): unimplemented in this platform");
1495 #endif /* #if defined(TIME_HIRES_CLOCK_GETTIME) */
1497 #if defined(TIME_HIRES_CLOCK_GETRES)
1500 clock_getres(clock_id = CLOCK_REALTIME)
1506 # ifdef TIME_HIRES_CLOCK_GETRES_SYSCALL
1507 status = syscall(SYS_clock_getres, clock_id, &ts);
1509 status = clock_getres(clock_id, &ts);
1511 RETVAL = status == 0 ? ts.tv_sec + (NV) ts.tv_nsec / NV_1E9 : -1;
1516 #else /* if defined(TIME_HIRES_CLOCK_GETRES) */
1519 clock_getres(clock_id = 0)
1522 PERL_UNUSED_ARG(clock_id);
1523 croak("Time::HiRes::clock_getres(): unimplemented in this platform");
1528 #endif /* #if defined(TIME_HIRES_CLOCK_GETRES) */
1530 #if defined(TIME_HIRES_CLOCK_NANOSLEEP) && defined(TIMER_ABSTIME)
1533 clock_nanosleep(clock_id, nsec, flags = 0)
1538 struct timespec sleepfor, unslept;
1541 croak("Time::HiRes::clock_nanosleep(..., %" NVgf
1542 "): negative time not invented yet", nsec);
1543 nanosleep_init(nsec, &sleepfor, &unslept);
1544 if (clock_nanosleep(clock_id, flags, &sleepfor, &unslept) == 0) {
1547 RETVAL = nsec_without_unslept(&sleepfor, &unslept);
1552 #else /* if defined(TIME_HIRES_CLOCK_NANOSLEEP) && defined(TIMER_ABSTIME) */
1555 clock_nanosleep(clock_id, nsec, flags = 0)
1560 PERL_UNUSED_ARG(clock_id);
1561 PERL_UNUSED_ARG(nsec);
1562 PERL_UNUSED_ARG(flags);
1563 croak("Time::HiRes::clock_nanosleep(): unimplemented in this platform");
1568 #endif /* #if defined(TIME_HIRES_CLOCK_NANOSLEEP) && defined(TIMER_ABSTIME) */
1570 #if defined(TIME_HIRES_CLOCK) && defined(CLOCKS_PER_SEC)
1578 RETVAL = clocks == (clock_t) -1 ? (clock_t) -1 : (NV)clocks / (NV)CLOCKS_PER_SEC;
1583 #else /* if defined(TIME_HIRES_CLOCK) && defined(CLOCKS_PER_SEC) */
1588 croak("Time::HiRes::clock(): unimplemented in this platform");
1593 #endif /* #if defined(TIME_HIRES_CLOCK) && defined(CLOCKS_PER_SEC) */
1602 Time::HiRes::lstat = 1
1604 XPUSHs(sv_2mortal(newSVsv(items == 1 ? ST(0) : DEFSV)));
1607 PL_laststatval = -1;
1609 Zero(&fakeop, 1, OP);
1610 fakeop.op_type = ix ? OP_LSTAT : OP_STAT;
1611 fakeop.op_ppaddr = PL_ppaddr[fakeop.op_type];
1612 fakeop.op_flags = GIMME_V == G_ARRAY ? OPf_WANT_LIST :
1613 GIMME_V == G_SCALAR ? OPf_WANT_SCALAR : OPf_WANT_VOID;
1615 (void)fakeop.op_ppaddr(aTHX);
1618 nret = SP+1 - &ST(0);
1620 UV atime = SvUV(ST( 8));
1621 UV mtime = SvUV(ST( 9));
1622 UV ctime = SvUV(ST(10));
1626 hrstatns(&atime_nsec, &mtime_nsec, &ctime_nsec);
1628 ST( 8) = sv_2mortal(newSVnv(atime + (NV) atime_nsec / NV_1E9));
1630 ST( 9) = sv_2mortal(newSVnv(mtime + (NV) mtime_nsec / NV_1E9));
1632 ST(10) = sv_2mortal(newSVnv(ctime + (NV) ctime_nsec / NV_1E9));