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
25 #if defined(__CYGWIN__) && defined(HAS_W32API_WINDOWS_H)
26 # include <w32api/windows.h>
27 # define CYGWIN_WITH_W32API
32 # include <sys/time.h>
36 # include <sys/select.h>
39 #if defined(TIME_HIRES_CLOCK_GETTIME_SYSCALL) || defined(TIME_HIRES_CLOCK_GETRES_SYSCALL)
46 #ifndef GCC_DIAG_IGNORE
47 # define GCC_DIAG_IGNORE(x)
48 # define GCC_DIAG_RESTORE
50 #ifndef GCC_DIAG_IGNORE_STMT
51 # define GCC_DIAG_IGNORE_STMT(x) GCC_DIAG_IGNORE(x) NOOP
52 # define GCC_DIAG_RESTORE_STMT GCC_DIAG_RESTORE NOOP
55 #if PERL_VERSION_GE(5,7,3) && !PERL_VERSION_GE(5,10,1)
57 # define SAVEOP() SAVEVPTR(PL_op)
60 #define IV_1E6 1000000
61 #define IV_1E7 10000000
62 #define IV_1E9 1000000000
64 #define NV_1E6 1000000.0
65 #define NV_1E7 10000000.0
66 #define NV_1E9 1000000000.0
68 #ifndef PerlProc_pause
69 # define PerlProc_pause() Pause()
75 # undef Pause /* In case perl.h did it already. */
76 # define Pause() sleep(~0) /* Zzz for a long time. */
79 /* Though the cpp define ITIMER_VIRTUAL is available the functionality
80 * is not supported in Cygwin as of August 2004, ditto for Win32.
81 * Neither are ITIMER_PROF or ITIMER_REALPROF implemented. --jhi
83 #if defined(__CYGWIN__) || defined(WIN32)
84 # undef ITIMER_VIRTUAL
86 # undef ITIMER_REALPROF
89 #ifndef ENV_LOCALE_LOCK
90 # define ENV_LOCALE_LOCK
92 #ifndef ENV_LOCALE_UNLOCK
93 # define ENV_LOCALE_UNLOCK
96 #ifndef TIME_HIRES_CLOCKID_T
97 typedef int clockid_t;
100 #if defined(TIME_HIRES_CLOCK_GETTIME) && defined(_STRUCT_ITIMERSPEC)
102 /* HP-UX has CLOCK_XXX values but as enums, not as defines.
103 * The only way to detect these would be to test compile for each. */
105 /* However, it seems that at least in HP-UX 11.31 ia64 there *are*
106 * defines for these, so let's try detecting them. */
107 # ifndef CLOCK_REALTIME
108 # define CLOCK_REALTIME CLOCK_REALTIME
109 # define CLOCK_VIRTUAL CLOCK_VIRTUAL
110 # define CLOCK_PROFILE CLOCK_PROFILE
112 # endif /* # ifdef __hpux */
114 #endif /* #if defined(TIME_HIRES_CLOCK_GETTIME) && defined(_STRUCT_ITIMERSPEC) */
116 #if defined(WIN32) || defined(CYGWIN_WITH_W32API)
118 # ifndef HAS_GETTIMEOFDAY
119 # define HAS_GETTIMEOFDAY
122 /* shows up in winsock.h?
130 unsigned __int64 ft_i64;
134 # define MY_CXT_KEY "Time::HiRes_" XS_VERSION
137 unsigned long run_count;
138 unsigned __int64 base_ticks;
139 unsigned __int64 tick_frequency;
140 FT_t base_systime_as_filetime;
141 unsigned __int64 reset_time;
144 /* Visual C++ 2013 and older don't have the timespec structure */
145 # if defined(_MSC_VER) && _MSC_VER < 1900
154 /* Number of 100 nanosecond units from 1/1/1601 to 1/1/1970 */
156 # define Const64(x) x##LL
158 # define Const64(x) x##i64
160 # define EPOCH_BIAS Const64(116444736000000000)
164 # define IV_1E6LL 1000000LL /* Needed because of Const64() ##-appends LL (or i64). */
165 # define IV_1E7LL 10000000LL
166 # define IV_1E9LL 1000000000LL
168 # define IV_1E6i64 1000000i64
169 # define IV_1E7i64 10000000i64
170 # define IV_1E9i64 1000000000i64
174 /* NOTE: This does not compute the timezone info (doing so can be expensive,
175 * and appears to be unsupported even by glibc) */
177 /* dMY_CXT needs a Perl context and we don't want to call PERL_GET_CONTEXT
178 for performance reasons */
181 # define gettimeofday(tp, not_used) _gettimeofday(aTHX_ tp, not_used)
183 # undef GetSystemTimePreciseAsFileTime
184 # define GetSystemTimePreciseAsFileTime(out) _GetSystemTimePreciseAsFileTime(aTHX_ out)
186 # undef clock_gettime
187 # define clock_gettime(clock_id, tp) _clock_gettime(aTHX_ clock_id, tp)
190 # define clock_getres(clock_id, tp) _clock_getres(clock_id, tp)
192 # ifndef CLOCK_REALTIME
193 # define CLOCK_REALTIME 1
194 # define CLOCK_MONOTONIC 2
197 /* If the performance counter delta drifts more than 0.5 seconds from the
198 * system time then we recalibrate to the system time. This means we may
199 * move *backwards* in time! */
200 # define MAX_PERF_COUNTER_SKEW Const64(5000000) /* 0.5 seconds */
202 /* Reset reading from the performance counter every five minutes.
203 * Many PC clocks just seem to be so bad. */
204 # define MAX_PERF_COUNTER_TICKS Const64(300000000) /* 300 seconds */
207 * Windows 8 introduced GetSystemTimePreciseAsFileTime(), but currently we have
208 * to support older systems, so for now we provide our own implementation.
209 * In the future we will switch to the real deal.
212 _GetSystemTimePreciseAsFileTime(pTHX_ FILETIME *out)
217 if (MY_CXT.run_count++ == 0 ||
218 MY_CXT.base_systime_as_filetime.ft_i64 > MY_CXT.reset_time) {
220 QueryPerformanceFrequency((LARGE_INTEGER*)&MY_CXT.tick_frequency);
221 QueryPerformanceCounter((LARGE_INTEGER*)&MY_CXT.base_ticks);
222 GetSystemTimeAsFileTime(&MY_CXT.base_systime_as_filetime.ft_val);
223 ft.ft_i64 = MY_CXT.base_systime_as_filetime.ft_i64;
224 MY_CXT.reset_time = ft.ft_i64 + MAX_PERF_COUNTER_TICKS;
228 unsigned __int64 ticks;
229 QueryPerformanceCounter((LARGE_INTEGER*)&ticks);
230 ticks -= MY_CXT.base_ticks;
231 ft.ft_i64 = MY_CXT.base_systime_as_filetime.ft_i64
232 + Const64(IV_1E7) * (ticks / MY_CXT.tick_frequency)
233 +(Const64(IV_1E7) * (ticks % MY_CXT.tick_frequency)) / MY_CXT.tick_frequency;
234 diff = ft.ft_i64 - MY_CXT.base_systime_as_filetime.ft_i64;
235 if (diff < -MAX_PERF_COUNTER_SKEW || diff > MAX_PERF_COUNTER_SKEW) {
236 MY_CXT.base_ticks += ticks;
237 GetSystemTimeAsFileTime(&MY_CXT.base_systime_as_filetime.ft_val);
238 ft.ft_i64 = MY_CXT.base_systime_as_filetime.ft_i64;
248 _gettimeofday(pTHX_ struct timeval *tp, void *not_used)
252 PERL_UNUSED_ARG(not_used);
254 GetSystemTimePreciseAsFileTime(&ft.ft_val);
256 /* seconds since epoch */
257 tp->tv_sec = (long)((ft.ft_i64 - EPOCH_BIAS) / Const64(IV_1E7));
259 /* microseconds remaining */
260 tp->tv_usec = (long)((ft.ft_i64 / Const64(10)) % Const64(IV_1E6));
266 _clock_gettime(pTHX_ clockid_t clock_id, struct timespec *tp)
271 case CLOCK_REALTIME: {
274 GetSystemTimePreciseAsFileTime(&ft.ft_val);
275 tp->tv_sec = (time_t)((ft.ft_i64 - EPOCH_BIAS) / IV_1E7);
276 tp->tv_nsec = (long)((ft.ft_i64 % IV_1E7) * 100);
279 case CLOCK_MONOTONIC: {
280 unsigned __int64 freq, ticks;
282 QueryPerformanceFrequency((LARGE_INTEGER*)&freq);
283 QueryPerformanceCounter((LARGE_INTEGER*)&ticks);
285 tp->tv_sec = (time_t)(ticks / freq);
286 tp->tv_nsec = (long)((IV_1E9 * (ticks % freq)) / freq);
298 _clock_getres(clockid_t clock_id, struct timespec *tp)
300 unsigned __int64 freq, qpc_res_ns;
302 QueryPerformanceFrequency((LARGE_INTEGER*)&freq);
303 qpc_res_ns = IV_1E9 > freq ? IV_1E9 / freq : 1;
308 /* the resolution can't be smaller than 100ns because our implementation
309 * of CLOCK_REALTIME is using FILETIME internally */
310 tp->tv_nsec = (long)(qpc_res_ns > 100 ? qpc_res_ns : 100);
313 case CLOCK_MONOTONIC:
315 tp->tv_nsec = (long)qpc_res_ns;
326 #endif /* #if defined(WIN32) || defined(CYGWIN_WITH_W32API) */
328 /* Do not use H A S _ N A N O S L E E P
329 * so that Perl Configure doesn't scan for it (and pull in -lrt and
330 * the like which are not usually good ideas for the default Perl).
331 * (We are part of the core perl now.)
332 * The TIME_HIRES_NANOSLEEP is set by Makefile.PL. */
333 #if !defined(HAS_USLEEP) && defined(TIME_HIRES_NANOSLEEP)
335 # define usleep hrt_usleep /* could conflict with ncurses for static build */
338 hrt_usleep(unsigned long usec) /* This is used to emulate usleep. */
341 res.tv_sec = usec / IV_1E6;
342 res.tv_nsec = ( usec - res.tv_sec * IV_1E6 ) * 1000;
343 nanosleep(&res, NULL);
346 #endif /* #if !defined(HAS_USLEEP) && defined(TIME_HIRES_NANOSLEEP) */
348 #if !defined(HAS_USLEEP) && defined(HAS_SELECT)
349 # ifndef SELECT_IS_BROKEN
351 # define usleep hrt_usleep /* could conflict with ncurses for static build */
354 hrt_usleep(unsigned long usec)
359 select(0, (Select_fd_set_t)NULL, (Select_fd_set_t)NULL,
360 (Select_fd_set_t)NULL, &tv);
363 #endif /* #if !defined(HAS_USLEEP) && defined(HAS_SELECT) */
365 #if !defined(HAS_USLEEP) && defined(WIN32)
367 # define usleep hrt_usleep /* could conflict with ncurses for static build */
370 hrt_usleep(unsigned long usec)
376 #endif /* #if !defined(HAS_USLEEP) && defined(WIN32) */
378 #if !defined(HAS_USLEEP) && defined(HAS_POLL)
380 # define usleep hrt_usleep /* could conflict with ncurses for static build */
383 hrt_usleep(unsigned long usec)
385 int msec = usec / 1000;
389 #endif /* #if !defined(HAS_USLEEP) && defined(HAS_POLL) */
391 #if defined(HAS_SETITIMER) && defined(ITIMER_REAL)
394 hrt_ualarm_itimero(struct itimerval *oitv, int usec, int uinterval)
396 struct itimerval itv;
397 itv.it_value.tv_sec = usec / IV_1E6;
398 itv.it_value.tv_usec = usec % IV_1E6;
399 itv.it_interval.tv_sec = uinterval / IV_1E6;
400 itv.it_interval.tv_usec = uinterval % IV_1E6;
401 return setitimer(ITIMER_REAL, &itv, oitv);
404 #endif /* #if !defined(HAS_UALARM) && defined(HAS_SETITIMER) */
406 #if !defined(HAS_UALARM) && defined(HAS_SETITIMER)
408 # define ualarm hrt_ualarm_itimer /* could conflict with ncurses for static build */
411 #if !defined(HAS_UALARM) && defined(VMS)
413 # define ualarm vms_ualarm
415 # include <lib$routines.h>
417 # include <starlet.h>
418 # include <descrip.h>
423 # define VMSERR(s) (!((s)&1))
426 us_to_VMS(useconds_t mseconds, unsigned long v[])
435 iss = lib$addx(qq,qq,qq);
436 if (VMSERR(iss)) lib$signal(iss);
437 iss = lib$subx(v,qq,v);
438 if (VMSERR(iss)) lib$signal(iss);
439 iss = lib$addx(qq,qq,qq);
440 if (VMSERR(iss)) lib$signal(iss);
441 iss = lib$subx(v,qq,v);
442 if (VMSERR(iss)) lib$signal(iss);
443 iss = lib$subx(v,qq,v);
444 if (VMSERR(iss)) lib$signal(iss);
448 VMS_to_us(unsigned long v[])
451 unsigned long div=10,quot, rem;
453 iss = lib$ediv(&div,v,",&rem);
454 if (VMSERR(iss)) lib$signal(iss);
459 typedef unsigned short word;
460 typedef struct _ualarm {
463 unsigned long delay[2];
464 unsigned long interval[2];
465 unsigned long remain[2];
470 static Alarm *a0, alarm_base;
474 # define UAL_ACTIVE 4
475 static void ualarm_AST(Alarm *a);
478 vms_ualarm(int mseconds, int interval)
487 static struct item_list3 itmlst[2];
488 static int first = 1;
494 itmlst[0].code = JPI$_ASTEN;
495 itmlst[0].length = sizeof(asten);
496 itmlst[0].retlenaddr = NULL;
498 itmlst[1].length = 0;
499 itmlst[1].bufaddr = NULL;
500 itmlst[1].retlenaddr = NULL;
502 iss = lib$get_ef(&alarm_ef);
503 if (VMSERR(iss)) lib$signal(iss);
506 a0->function = UAL_NULL;
508 itmlst[0].bufaddr = &asten;
510 iss = sys$getjpiw(0,0,0,itmlst,0,0,0);
511 if (VMSERR(iss)) lib$signal(iss);
512 if (!(asten&0x08)) return -1;
516 a->function = UAL_SET;
518 a->function = UAL_CLEAR;
521 us_to_VMS(mseconds, a->delay);
523 us_to_VMS(interval, a->interval);
528 iss = sys$clref(alarm_ef);
529 if (VMSERR(iss)) lib$signal(iss);
531 iss = sys$dclast(ualarm_AST,a,0);
532 if (VMSERR(iss)) lib$signal(iss);
534 iss = sys$waitfr(alarm_ef);
535 if (VMSERR(iss)) lib$signal(iss);
537 if (a->function == UAL_ACTIVE)
538 return VMS_to_us(a->remain);
549 unsigned long now[2];
551 iss = sys$gettim(now);
552 if (VMSERR(iss)) lib$signal(iss);
554 if (a->function == UAL_SET || a->function == UAL_CLEAR) {
555 if (a0->function == UAL_ACTIVE) {
556 iss = sys$cantim(a0,PSL$C_USER);
557 if (VMSERR(iss)) lib$signal(iss);
559 iss = lib$subx(a0->remain, now, a->remain);
560 if (VMSERR(iss)) lib$signal(iss);
562 if (a->remain[1] & 0x80000000)
563 a->remain[0] = a->remain[1] = 0;
566 if (a->function == UAL_SET) {
567 a->function = a0->function;
568 a0->function = UAL_ACTIVE;
569 a0->repeat = a->repeat;
571 a0->interval[0] = a->interval[0];
572 a0->interval[1] = a->interval[1];
574 a0->delay[0] = a->delay[0];
575 a0->delay[1] = a->delay[1];
577 iss = lib$subx(now, a0->delay, a0->remain);
578 if (VMSERR(iss)) lib$signal(iss);
580 iss = sys$setimr(0,a0->delay,ualarm_AST,a0);
581 if (VMSERR(iss)) lib$signal(iss);
583 a->function = a0->function;
584 a0->function = UAL_NULL;
586 iss = sys$setef(alarm_ef);
587 if (VMSERR(iss)) lib$signal(iss);
588 } else if (a->function == UAL_ACTIVE) {
590 iss = lib$subx(now, a->interval, a->remain);
591 if (VMSERR(iss)) lib$signal(iss);
593 iss = sys$setimr(0,a->interval,ualarm_AST,a);
594 if (VMSERR(iss)) lib$signal(iss);
596 a->function = UAL_NULL;
599 if (VMSERR(iss)) lib$signal(iss);
600 lib$signal(SS$_ASTFLT);
602 lib$signal(SS$_BADPARAM);
606 #endif /* #if !defined(HAS_UALARM) && defined(VMS) */
608 #ifdef HAS_GETTIMEOFDAY
611 myU2time(pTHX_ UV *ret)
615 status = gettimeofday (&Tp, NULL);
629 status = gettimeofday (&Tp, NULL);
630 return status == 0 ? Tp.tv_sec + (Tp.tv_usec / NV_1E6) : -1.0;
633 #endif /* #ifdef HAS_GETTIMEOFDAY */
636 hrstatns(UV *atime_nsec, UV *mtime_nsec, UV *ctime_nsec)
639 #if TIME_HIRES_STAT == 1
640 *atime_nsec = PL_statcache.st_atimespec.tv_nsec;
641 *mtime_nsec = PL_statcache.st_mtimespec.tv_nsec;
642 *ctime_nsec = PL_statcache.st_ctimespec.tv_nsec;
643 #elif TIME_HIRES_STAT == 2
644 *atime_nsec = PL_statcache.st_atimensec;
645 *mtime_nsec = PL_statcache.st_mtimensec;
646 *ctime_nsec = PL_statcache.st_ctimensec;
647 #elif TIME_HIRES_STAT == 3
648 *atime_nsec = PL_statcache.st_atime_n;
649 *mtime_nsec = PL_statcache.st_mtime_n;
650 *ctime_nsec = PL_statcache.st_ctime_n;
651 #elif TIME_HIRES_STAT == 4
652 *atime_nsec = PL_statcache.st_atim.tv_nsec;
653 *mtime_nsec = PL_statcache.st_mtim.tv_nsec;
654 *ctime_nsec = PL_statcache.st_ctim.tv_nsec;
655 #elif TIME_HIRES_STAT == 5
656 *atime_nsec = PL_statcache.st_uatime * 1000;
657 *mtime_nsec = PL_statcache.st_umtime * 1000;
658 *ctime_nsec = PL_statcache.st_uctime * 1000;
659 #else /* !TIME_HIRES_STAT */
663 #endif /* !TIME_HIRES_STAT */
666 /* Until Apple implements clock_gettime()
667 * (ditto clock_getres() and clock_nanosleep())
668 * we will emulate them using the Mach kernel interfaces. */
669 #if defined(PERL_DARWIN) && \
670 (defined(TIME_HIRES_CLOCK_GETTIME_EMULATION) || \
671 defined(TIME_HIRES_CLOCK_GETRES_EMULATION) || \
672 defined(TIME_HIRES_CLOCK_NANOSLEEP_EMULATION))
674 # ifndef CLOCK_REALTIME
675 # define CLOCK_REALTIME 0x01
676 # define CLOCK_MONOTONIC 0x02
679 # ifndef TIMER_ABSTIME
680 # define TIMER_ABSTIME 0x01
684 # define PERL_DARWIN_MUTEX
687 # ifdef PERL_DARWIN_MUTEX
688 STATIC perl_mutex darwin_time_mutex;
691 # include <mach/mach_time.h>
693 static uint64_t absolute_time_init;
694 static mach_timebase_info_data_t timebase_info;
695 static struct timespec timespec_init;
697 static int darwin_time_init() {
700 # ifdef PERL_DARWIN_MUTEX
701 MUTEX_LOCK(&darwin_time_mutex);
703 if (absolute_time_init == 0) {
704 /* mach_absolute_time() cannot fail */
705 absolute_time_init = mach_absolute_time();
706 success = mach_timebase_info(&timebase_info) == KERN_SUCCESS;
708 success = gettimeofday(&tv, NULL) == 0;
710 timespec_init.tv_sec = tv.tv_sec;
711 timespec_init.tv_nsec = tv.tv_usec * 1000;
715 # ifdef PERL_DARWIN_MUTEX
716 MUTEX_UNLOCK(&darwin_time_mutex);
721 # ifdef TIME_HIRES_CLOCK_GETTIME_EMULATION
722 static int th_clock_gettime(clockid_t clock_id, struct timespec *ts) {
723 if (darwin_time_init() && timebase_info.denom) {
728 ((mach_absolute_time() - absolute_time_init) *
729 (uint64_t)timebase_info.numer) / (uint64_t)timebase_info.denom;
730 ts->tv_sec = timespec_init.tv_sec + nanos / IV_1E9;
731 ts->tv_nsec = timespec_init.tv_nsec + nanos % IV_1E9;
735 case CLOCK_MONOTONIC:
738 (mach_absolute_time() *
739 (uint64_t)timebase_info.numer) / (uint64_t)timebase_info.denom;
740 ts->tv_sec = nanos / IV_1E9;
741 ts->tv_nsec = nanos - ts->tv_sec * IV_1E9;
750 SETERRNO(EINVAL, LIB_INVARG);
754 # define clock_gettime(clock_id, ts) th_clock_gettime((clock_id), (ts))
756 # endif /* TIME_HIRES_CLOCK_GETTIME_EMULATION */
758 # ifdef TIME_HIRES_CLOCK_GETRES_EMULATION
759 static int th_clock_getres(clockid_t clock_id, struct timespec *ts) {
760 if (darwin_time_init() && timebase_info.denom) {
763 case CLOCK_MONOTONIC:
765 /* In newer kernels both the numer and denom are one,
766 * resulting in conversion factor of one, which is of
767 * course unrealistic. */
768 ts->tv_nsec = timebase_info.numer / timebase_info.denom;
775 SETERRNO(EINVAL, LIB_INVARG);
779 # define clock_getres(clock_id, ts) th_clock_getres((clock_id), (ts))
780 # endif /* TIME_HIRES_CLOCK_GETRES_EMULATION */
782 # ifdef TIME_HIRES_CLOCK_NANOSLEEP_EMULATION
783 static int th_clock_nanosleep(clockid_t clock_id, int flags,
784 const struct timespec *rqtp,
785 struct timespec *rmtp) {
786 if (darwin_time_init()) {
789 case CLOCK_MONOTONIC:
791 uint64_t nanos = rqtp->tv_sec * IV_1E9 + rqtp->tv_nsec;
793 if ((flags & TIMER_ABSTIME)) {
795 timespec_init.tv_sec * IV_1E9 + timespec_init.tv_nsec;
796 nanos = nanos > back ? nanos - back : 0;
799 mach_wait_until(mach_absolute_time() + nanos) == KERN_SUCCESS;
801 /* In the relative sleep, the rmtp should be filled in with
802 * the 'unused' part of the rqtp in case the sleep gets
803 * interrupted by a signal. But it is unknown how signals
804 * interact with mach_wait_until(). In the absolute sleep,
805 * the rmtp should stay untouched. */
817 SETERRNO(EINVAL, LIB_INVARG);
821 # define clock_nanosleep(clock_id, flags, rqtp, rmtp) \
822 th_clock_nanosleep((clock_id), (flags), (rqtp), (rmtp))
824 # endif /* TIME_HIRES_CLOCK_NANOSLEEP_EMULATION */
826 #endif /* PERL_DARWIN */
828 /* The macOS headers warn about using certain interfaces in
829 * OS-release-ignorant manner, for example:
831 * warning: 'futimens' is only available on macOS 10.13 or newer
832 * [-Wunguarded-availability-new]
834 * (ditto for utimensat)
836 * There is clang __builtin_available() *runtime* check for this.
837 * The gotchas are that neither __builtin_available() nor __has_builtin()
838 * are always available.
840 #ifndef __has_builtin
841 # define __has_builtin(x) 0 /* non-clang */
844 # if defined(PERL_DARWIN) && __has_builtin(__builtin_available)
845 # define FUTIMENS_AVAILABLE __builtin_available(macOS 10.13, *)
847 # define FUTIMENS_AVAILABLE 1
850 # define FUTIMENS_AVAILABLE 0
853 # if defined(PERL_DARWIN) && __has_builtin(__builtin_available)
854 # define UTIMENSAT_AVAILABLE __builtin_available(macOS 10.13, *)
856 # define UTIMENSAT_AVAILABLE 1
859 # define UTIMENSAT_AVAILABLE 0
862 #include "const-c.inc"
864 #if (defined(TIME_HIRES_NANOSLEEP)) || \
865 (defined(TIME_HIRES_CLOCK_NANOSLEEP) && defined(TIMER_ABSTIME))
868 nanosleep_init(NV nsec,
869 struct timespec *sleepfor,
870 struct timespec *unslept) {
871 sleepfor->tv_sec = (Time_t)(nsec / NV_1E9);
872 sleepfor->tv_nsec = (long)(nsec - ((NV)sleepfor->tv_sec) * NV_1E9);
874 unslept->tv_nsec = 0;
878 nsec_without_unslept(struct timespec *sleepfor,
879 const struct timespec *unslept) {
880 if (sleepfor->tv_sec >= unslept->tv_sec) {
881 sleepfor->tv_sec -= unslept->tv_sec;
882 if (sleepfor->tv_nsec >= unslept->tv_nsec) {
883 sleepfor->tv_nsec -= unslept->tv_nsec;
884 } else if (sleepfor->tv_sec > 0) {
886 sleepfor->tv_nsec += IV_1E9;
887 sleepfor->tv_nsec -= unslept->tv_nsec;
889 sleepfor->tv_sec = 0;
890 sleepfor->tv_nsec = 0;
893 sleepfor->tv_sec = 0;
894 sleepfor->tv_nsec = 0;
896 return ((NV)sleepfor->tv_sec) * NV_1E9 + ((NV)sleepfor->tv_nsec);
901 /* In case Perl and/or Devel::PPPort are too old, minimally emulate
902 * IS_SAFE_PATHNAME() (which looks for zero bytes in the pathname). */
903 #ifndef IS_SAFE_PATHNAME
904 # if PERL_VERSION_GE(5,12,0) /* Perl_ck_warner is 5.10.0 -> */
905 # ifdef WARN_SYSCALLS
906 # define WARNEMUCAT WARN_SYSCALLS /* 5.22.0 -> */
908 # define WARNEMUCAT WARN_MISC
910 # define WARNEMU(opname) Perl_ck_warner(aTHX_ packWARN(WARNEMUCAT), "Invalid \\0 character in pathname for %s",opname)
912 # define WARNEMU(opname) Perl_warn(aTHX_ "Invalid \\0 character in pathname for %s",opname)
914 # define IS_SAFE_PATHNAME(pv, len, opname) (((len)>1)&&memchr((pv), 0, (len)-1)?(SETERRNO(ENOENT, LIB_INVARG),WARNEMU(opname),FALSE):(TRUE))
917 MODULE = Time::HiRes PACKAGE = Time::HiRes
926 #ifdef HAS_GETTIMEOFDAY
928 (void) hv_store(PL_modglobal, "Time::NVtime", 12,
929 newSViv(PTR2IV(myNVtime)), 0);
930 (void) hv_store(PL_modglobal, "Time::U2time", 12,
931 newSViv(PTR2IV(myU2time)), 0);
934 #if defined(PERL_DARWIN)
935 # if defined(USE_ITHREADS) && defined(PERL_DARWIN_MUTEX)
936 MUTEX_INIT(&darwin_time_mutex);
941 #if defined(USE_ITHREADS) && defined(MY_CXT_KEY)
950 INCLUDE: const-xs.inc
952 #if defined(HAS_USLEEP) && defined(HAS_GETTIMEOFDAY)
958 struct timeval Ta, Tb;
960 gettimeofday(&Ta, NULL);
962 if (useconds >= NV_1E6) {
963 IV seconds = (IV) (useconds / NV_1E6);
964 /* If usleep() has been implemented using setitimer()
965 * then this contortion is unnecessary-- but usleep()
966 * may be implemented in some other way, so let's contort. */
969 useconds -= NV_1E6 * seconds;
971 } else if (useconds < 0.0)
972 croak("Time::HiRes::usleep(%" NVgf
973 "): negative time not invented yet", useconds);
975 usleep((U32)useconds);
979 gettimeofday(&Tb, NULL);
981 printf("[%ld %ld] [%ld %ld]\n", Tb.tv_sec, Tb.tv_usec, Ta.tv_sec, Ta.tv_usec);
983 RETVAL = NV_1E6*(Tb.tv_sec-Ta.tv_sec)+(NV)((IV)Tb.tv_usec-(IV)Ta.tv_usec);
988 # if defined(TIME_HIRES_NANOSLEEP)
994 struct timespec sleepfor, unslept;
997 croak("Time::HiRes::nanosleep(%" NVgf
998 "): negative time not invented yet", nsec);
999 nanosleep_init(nsec, &sleepfor, &unslept);
1000 if (nanosleep(&sleepfor, &unslept) == 0) {
1003 RETVAL = nsec_without_unslept(&sleepfor, &unslept);
1008 # else /* #if defined(TIME_HIRES_NANOSLEEP) */
1014 PERL_UNUSED_ARG(nsec);
1015 croak("Time::HiRes::nanosleep(): unimplemented in this platform");
1020 # endif /* #if defined(TIME_HIRES_NANOSLEEP) */
1025 struct timeval Ta, Tb;
1027 gettimeofday(&Ta, NULL);
1029 NV seconds = SvNV(ST(0));
1030 if (seconds >= 0.0) {
1031 UV useconds = (UV)(1E6 * (seconds - (UV)seconds));
1033 sleep((U32)seconds);
1034 if ((IV)useconds < 0) {
1035 # if defined(__sparc64__) && defined(__GNUC__)
1036 /* Sparc64 gcc 2.95.3 (e.g. on NetBSD) has a bug
1037 * where (0.5 - (UV)(0.5)) will under certain
1038 * circumstances (if the double is cast to UV more
1039 * than once?) evaluate to -0.5, instead of 0.5. */
1040 useconds = -(IV)useconds;
1041 # endif /* #if defined(__sparc64__) && defined(__GNUC__) */
1042 if ((IV)useconds < 0)
1043 croak("Time::HiRes::sleep(%" NVgf
1044 "): internal error: useconds < 0 (unsigned %" UVuf
1045 " signed %" IVdf ")",
1046 seconds, useconds, (IV)useconds);
1050 croak("Time::HiRes::sleep(%" NVgf
1051 "): negative time not invented yet", seconds);
1055 gettimeofday(&Tb, NULL);
1057 printf("[%ld %ld] [%ld %ld]\n", Tb.tv_sec, Tb.tv_usec, Ta.tv_sec, Ta.tv_usec);
1059 RETVAL = (NV)(Tb.tv_sec-Ta.tv_sec)+0.000001*(NV)(Tb.tv_usec-Ta.tv_usec);
1064 #else /* #if defined(HAS_USLEEP) && defined(HAS_GETTIMEOFDAY) */
1070 PERL_UNUSED_ARG(useconds);
1071 croak("Time::HiRes::usleep(): unimplemented in this platform");
1076 #endif /* #if defined(HAS_USLEEP) && defined(HAS_GETTIMEOFDAY) */
1081 ualarm(useconds,uinterval=0)
1085 if (useconds < 0 || uinterval < 0)
1086 croak("Time::HiRes::ualarm(%d, %d): negative time not invented yet", useconds, uinterval);
1087 # if defined(HAS_SETITIMER) && defined(ITIMER_REAL)
1089 struct itimerval itv;
1090 if (hrt_ualarm_itimero(&itv, useconds, uinterval)) {
1091 /* To conform to ualarm's interface, we're actually ignoring
1095 RETVAL = itv.it_value.tv_sec * IV_1E6 + itv.it_value.tv_usec;
1099 if (useconds >= IV_1E6 || uinterval >= IV_1E6)
1100 croak("Time::HiRes::ualarm(%d, %d): useconds or uinterval"
1101 " equal to or more than %" IVdf,
1102 useconds, uinterval, IV_1E6);
1104 RETVAL = ualarm(useconds, uinterval);
1111 alarm(seconds,interval=0)
1115 if (seconds < 0.0 || interval < 0.0)
1116 croak("Time::HiRes::alarm(%" NVgf ", %" NVgf
1117 "): negative time not invented yet", seconds, interval);
1120 IV iseconds = (IV)seconds;
1121 IV iinterval = (IV)interval;
1122 NV fseconds = seconds - iseconds;
1123 NV finterval = interval - iinterval;
1124 IV useconds, uinterval;
1125 if (fseconds >= 1.0 || finterval >= 1.0)
1126 croak("Time::HiRes::alarm(%" NVgf ", %" NVgf
1127 "): seconds or interval too large to split correctly",
1130 useconds = IV_1E6 * fseconds;
1131 uinterval = IV_1E6 * finterval;
1132 # if defined(HAS_SETITIMER) && defined(ITIMER_REAL)
1134 struct itimerval nitv, oitv;
1135 nitv.it_value.tv_sec = iseconds;
1136 nitv.it_value.tv_usec = useconds;
1137 nitv.it_interval.tv_sec = iinterval;
1138 nitv.it_interval.tv_usec = uinterval;
1139 if (setitimer(ITIMER_REAL, &nitv, &oitv)) {
1140 /* To conform to alarm's interface, we're actually ignoring
1144 RETVAL = oitv.it_value.tv_sec + ((NV)oitv.it_value.tv_usec) / NV_1E6;
1148 if (iseconds || iinterval)
1149 croak("Time::HiRes::alarm(%" NVgf ", %" NVgf
1150 "): seconds or interval equal to or more than 1.0 ",
1153 RETVAL = (NV)ualarm( useconds, uinterval ) / NV_1E6;
1160 #else /* #ifdef HAS_UALARM */
1163 ualarm(useconds,interval=0)
1167 PERL_UNUSED_ARG(useconds);
1168 PERL_UNUSED_ARG(interval);
1169 croak("Time::HiRes::ualarm(): unimplemented in this platform");
1175 alarm(seconds,interval=0)
1179 PERL_UNUSED_ARG(seconds);
1180 PERL_UNUSED_ARG(interval);
1181 croak("Time::HiRes::alarm(): unimplemented in this platform");
1186 #endif /* #ifdef HAS_UALARM */
1188 #ifdef HAS_GETTIMEOFDAY
1196 status = gettimeofday (&Tp, NULL);
1198 if (GIMME == G_ARRAY) {
1200 PUSHs(sv_2mortal(newSViv(Tp.tv_sec)));
1201 PUSHs(sv_2mortal(newSViv(Tp.tv_usec)));
1204 PUSHs(sv_2mortal(newSVnv(Tp.tv_sec + (Tp.tv_usec / NV_1E6))));
1214 status = gettimeofday (&Tp, NULL);
1216 RETVAL = Tp.tv_sec + (Tp.tv_usec / NV_1E6);
1223 #endif /* #ifdef HAS_GETTIMEOFDAY */
1225 #if defined(HAS_GETITIMER) && defined(HAS_SETITIMER)
1227 # define TV2NV(tv) ((NV)((tv).tv_sec) + 0.000001 * (NV)((tv).tv_usec))
1230 setitimer(which, seconds, interval = 0)
1235 struct itimerval newit;
1236 struct itimerval oldit;
1238 if (seconds < 0.0 || interval < 0.0)
1239 croak("Time::HiRes::setitimer(%" IVdf ", %" NVgf ", %" NVgf
1240 "): negative time not invented yet",
1241 (IV)which, seconds, interval);
1242 newit.it_value.tv_sec = (IV)seconds;
1243 newit.it_value.tv_usec =
1244 (IV)((seconds - (NV)newit.it_value.tv_sec) * NV_1E6);
1245 newit.it_interval.tv_sec = (IV)interval;
1246 newit.it_interval.tv_usec =
1247 (IV)((interval - (NV)newit.it_interval.tv_sec) * NV_1E6);
1248 /* on some platforms the 1st arg to setitimer is an enum, which
1249 * causes -Wc++-compat to complain about passing an int instead
1251 GCC_DIAG_IGNORE_STMT(-Wc++-compat);
1252 if (setitimer(which, &newit, &oldit) == 0) {
1254 PUSHs(sv_2mortal(newSVnv(TV2NV(oldit.it_value))));
1255 if (GIMME == G_ARRAY) {
1257 PUSHs(sv_2mortal(newSVnv(TV2NV(oldit.it_interval))));
1260 GCC_DIAG_RESTORE_STMT;
1266 struct itimerval nowit;
1268 /* on some platforms the 1st arg to getitimer is an enum, which
1269 * causes -Wc++-compat to complain about passing an int instead
1271 GCC_DIAG_IGNORE_STMT(-Wc++-compat);
1272 if (getitimer(which, &nowit) == 0) {
1274 PUSHs(sv_2mortal(newSVnv(TV2NV(nowit.it_value))));
1275 if (GIMME == G_ARRAY) {
1277 PUSHs(sv_2mortal(newSVnv(TV2NV(nowit.it_interval))));
1280 GCC_DIAG_RESTORE_STMT;
1282 #endif /* #if defined(HAS_GETITIMER) && defined(HAS_SETITIMER) */
1284 #if defined(TIME_HIRES_UTIME)
1287 utime(accessed, modified, ...)
1294 struct timespec utbuf[2];
1295 struct timespec *utbufp = utbuf;
1304 if ( accessed == &PL_sv_undef && modified == &PL_sv_undef )
1307 if (SvNV(accessed) < 0.0 || SvNV(modified) < 0.0)
1308 croak("Time::HiRes::utime(%" NVgf ", %" NVgf
1309 "): negative time not invented yet",
1310 SvNV(accessed), SvNV(modified));
1311 Zero(&utbuf, sizeof utbuf, char);
1313 utbuf[0].tv_sec = (Time_t)SvNV(accessed); /* time accessed */
1314 utbuf[0].tv_nsec = (long)(
1315 (SvNV(accessed) - (NV)utbuf[0].tv_sec)
1316 * NV_1E9 + (NV)0.5);
1318 utbuf[1].tv_sec = (Time_t)SvNV(modified); /* time modified */
1319 utbuf[1].tv_nsec = (long)(
1320 (SvNV(modified) - (NV)utbuf[1].tv_sec)
1321 * NV_1E9 + (NV)0.5);
1325 file = POPs; items--;
1327 if (SvROK(file) && GvIO(SvRV(file)) && IoIFP(sv_2io(SvRV(file)))) {
1328 int fd = PerlIO_fileno(IoIFP(sv_2io(file)));
1330 SETERRNO(EBADF,RMS_IFI);
1332 # ifdef HAS_FUTIMENS
1333 if (FUTIMENS_AVAILABLE) {
1334 if (futimens(fd, utbufp) == 0) {
1338 croak("futimens unimplemented in this platform");
1340 # else /* HAS_FUTIMENS */
1341 croak("futimens unimplemented in this platform");
1342 # endif /* HAS_FUTIMENS */
1346 # ifdef HAS_UTIMENSAT
1347 if (UTIMENSAT_AVAILABLE) {
1349 char * name = SvPV(file, len);
1350 if (IS_SAFE_PATHNAME(name, len, "utime") &&
1351 utimensat(AT_FDCWD, name, utbufp, 0) == 0) {
1356 croak("utimensat unimplemented in this platform");
1358 # else /* HAS_UTIMENSAT */
1359 croak("utimensat unimplemented in this platform");
1360 # endif /* HAS_UTIMENSAT */
1368 #else /* #if defined(TIME_HIRES_UTIME) */
1371 utime(accessed, modified, ...)
1373 croak("Time::HiRes::utime(): unimplemented in this platform");
1378 #endif /* #if defined(TIME_HIRES_UTIME) */
1380 #if defined(TIME_HIRES_CLOCK_GETTIME)
1383 clock_gettime(clock_id = CLOCK_REALTIME)
1389 # ifdef TIME_HIRES_CLOCK_GETTIME_SYSCALL
1390 status = syscall(SYS_clock_gettime, clock_id, &ts);
1392 status = clock_gettime(clock_id, &ts);
1394 RETVAL = status == 0 ? ts.tv_sec + (NV) ts.tv_nsec / NV_1E9 : -1;
1399 #else /* if defined(TIME_HIRES_CLOCK_GETTIME) */
1402 clock_gettime(clock_id = 0)
1405 PERL_UNUSED_ARG(clock_id);
1406 croak("Time::HiRes::clock_gettime(): unimplemented in this platform");
1411 #endif /* #if defined(TIME_HIRES_CLOCK_GETTIME) */
1413 #if defined(TIME_HIRES_CLOCK_GETRES)
1416 clock_getres(clock_id = CLOCK_REALTIME)
1422 # ifdef TIME_HIRES_CLOCK_GETRES_SYSCALL
1423 status = syscall(SYS_clock_getres, clock_id, &ts);
1425 status = clock_getres(clock_id, &ts);
1427 RETVAL = status == 0 ? ts.tv_sec + (NV) ts.tv_nsec / NV_1E9 : -1;
1432 #else /* if defined(TIME_HIRES_CLOCK_GETRES) */
1435 clock_getres(clock_id = 0)
1438 PERL_UNUSED_ARG(clock_id);
1439 croak("Time::HiRes::clock_getres(): unimplemented in this platform");
1444 #endif /* #if defined(TIME_HIRES_CLOCK_GETRES) */
1446 #if defined(TIME_HIRES_CLOCK_NANOSLEEP) && defined(TIMER_ABSTIME)
1449 clock_nanosleep(clock_id, nsec, flags = 0)
1454 struct timespec sleepfor, unslept;
1457 croak("Time::HiRes::clock_nanosleep(..., %" NVgf
1458 "): negative time not invented yet", nsec);
1459 nanosleep_init(nsec, &sleepfor, &unslept);
1460 if (clock_nanosleep(clock_id, flags, &sleepfor, &unslept) == 0) {
1463 RETVAL = nsec_without_unslept(&sleepfor, &unslept);
1468 #else /* if defined(TIME_HIRES_CLOCK_NANOSLEEP) && defined(TIMER_ABSTIME) */
1471 clock_nanosleep(clock_id, nsec, flags = 0)
1476 PERL_UNUSED_ARG(clock_id);
1477 PERL_UNUSED_ARG(nsec);
1478 PERL_UNUSED_ARG(flags);
1479 croak("Time::HiRes::clock_nanosleep(): unimplemented in this platform");
1484 #endif /* #if defined(TIME_HIRES_CLOCK_NANOSLEEP) && defined(TIMER_ABSTIME) */
1486 #if defined(TIME_HIRES_CLOCK) && defined(CLOCKS_PER_SEC)
1494 RETVAL = clocks == (clock_t) -1 ? (clock_t) -1 : (NV)clocks / (NV)CLOCKS_PER_SEC;
1499 #else /* if defined(TIME_HIRES_CLOCK) && defined(CLOCKS_PER_SEC) */
1504 croak("Time::HiRes::clock(): unimplemented in this platform");
1509 #endif /* #if defined(TIME_HIRES_CLOCK) && defined(CLOCKS_PER_SEC) */
1518 Time::HiRes::lstat = 1
1520 XPUSHs(sv_2mortal(newSVsv(items == 1 ? ST(0) : DEFSV)));
1523 PL_laststatval = -1;
1525 Zero(&fakeop, 1, OP);
1526 fakeop.op_type = ix ? OP_LSTAT : OP_STAT;
1527 fakeop.op_ppaddr = PL_ppaddr[fakeop.op_type];
1528 fakeop.op_flags = GIMME_V == G_ARRAY ? OPf_WANT_LIST :
1529 GIMME_V == G_SCALAR ? OPf_WANT_SCALAR : OPf_WANT_VOID;
1531 (void)fakeop.op_ppaddr(aTHX);
1534 nret = SP+1 - &ST(0);
1536 UV atime = SvUV(ST( 8));
1537 UV mtime = SvUV(ST( 9));
1538 UV ctime = SvUV(ST(10));
1542 hrstatns(&atime_nsec, &mtime_nsec, &ctime_nsec);
1544 ST( 8) = sv_2mortal(newSVnv(atime + (NV) atime_nsec / NV_1E9));
1546 ST( 9) = sv_2mortal(newSVnv(mtime + (NV) mtime_nsec / NV_1E9));
1548 ST(10) = sv_2mortal(newSVnv(ctime + (NV) ctime_nsec / NV_1E9));