[Git][ghc/ghc][wip/dcoutts/posix-time] 15 commits: Make clock_gettime required on posix platforms
Duncan Coutts pushed to branch wip/dcoutts/posix-time at Glasgow Haskell Compiler / GHC Commits: dd0c5570 by Duncan Coutts at 2026-11-11T20:54:46+00:00 Make clock_gettime required on posix platforms It was defined in POSIX.1-2001 and has been manditory since POSIX.1-2008. We will rely on CLOCK_MONOTONIC for the RTS-internal monotonic time source. On macOS it has been available since 10.12 released in 2016 (and EOL 2019). We already have 11.0 as our minimum version for which we build binaries (MACOSX_DEPLOYMENT_TARGET=11.0). Also we must now drop the workaround from #12858 that would make the CI configuration invoke configure in a way that would always fail to detect clock_gettime (since obviously now we must detect it). Re-generate the gitlab jobs files for the benefit of CI. - - - - - 4ba04ba8 by Duncan Coutts at 2026-11-11T20:55:43+00:00 Simplify time code based on assuming defined(HAVE_CLOCK_GETTIME) No need to fall back to gettimeofday or times - - - - - 5c0e3247 by Duncan Coutts at 2026-11-11T20:55:43+00:00 Use clock_gettime CLOCK_REALTIME for getUnixEpochTime - - - - - 241f89fb by Duncan Coutts at 2026-11-11T20:55:44+00:00 Simplify getCurrentThreadCPUTime to use clock_gettime except on Solaris where it doesn't work. In particular, this means we now use it on macOS. It apparently works there from 10.12 onwards. We drop the check for clock_getcpuclockid which is linux-specific, archaic, and in any case isn't necessarily fatal. - - - - - 85c74f38 by Duncan Coutts at 2026-11-11T20:55:44+00:00 Remove now-redundant darwin time code - - - - - e2026fc7 by Duncan Coutts at 2026-11-11T20:55:44+00:00 Simplify getProcessCPUTime to use clock_gettime CLOCK_PROCESS_CPUTIME_ID It would be nice to check during startup using sysconf that this is really available. Unfortunately this doesn't actually work on macOS: it reports via sysconf that it is not available, when actually it is. Great. - - - - - 770fed8c by Duncan Coutts at 2026-11-11T20:55:44+00:00 Tidy up GetTime.c headers and Clock.h No longer need to define CLOCK_ID. Do the same for HsBase.h, where CLOCK_ID does not appear to be used at all. - - - - - 98205ed3 by Duncan Coutts at 2026-11-11T20:55:44+00:00 Remove posix/Clock.h entirely Not needed. - - - - - cb29c3f2 by Duncan Coutts at 2026-11-11T20:55:44+00:00 Split getPageFaults out into OSStats.{h,c} Strictly speaking it never had any business living with the time functions. It was merely convenience. Moving it out allows the remainder to use PosixSource.h (at least on posix). - - - - - cd19d575 by Duncan Coutts at 2026-11-11T20:55:44+00:00 Move getProcessTimes to its only use site Historically getProcessTimes made sense, since the main way to get the elapsed time would also get the cpu time as well. After recent time code simplification on posix then in all platforms it is just the pair of getProcessCPUTime and getProcessElapsedTime separarely. So we can remove three identical implementations and move it to be a local function in Stats.c where it is used. - - - - - c7ee1cb1 by Duncan Coutts at 2026-11-11T20:55:44+00:00 Improve win32 implementation of getMonotonicNSec We don't need the fallback GetTickCount method. Fixes #14233 - - - - - 59ad64d1 by Duncan Coutts at 2026-11-11T20:55:44+00:00 Improve win32 implementation of getUnixEpochTime We can now use GetSystemTimePreciseAsFileTime, which is supported from Windows 8 onwards. This is the recommendation from MS. - - - - - 8e9bb0e4 by Duncan Coutts at 2026-11-11T20:55:44+00:00 Remove initializeTimer It is now a no-op on all platforms. - - - - - d956273c by Duncan Coutts at 2026-11-11T20:55:44+00:00 Remove unused rtsSleep utility - - - - - 8d807650 by Duncan Coutts at 2026-11-11T20:55:44+00:00 Make the "get the time" functions more consistent We had: Time getProcessElapsedTime(void); // pulbic StgWord64 getMonotonicNSec(void); // public void getUnixEpochTime(StgWord64 *sec, StgWord32 *nsec); // internal These don't follow any naming convention, nor any common type convention. Now we have: Time getMonotonicTime(void); // internal Time getWallClockTime(void); // internal StgWord64 getMonotonicNSec(void); // public compat alias Time getProcessElapsedTime(void); // public compat alias Now the two main ones use a common representation: Time which is int64_t nanoseconds since the epoch. And their names better reflect that they use different clocks: a monotonic clock, or a real time / wall clock. We keep getMonotonicNSec and getProcessElapsedTime as aliases for getMonotonicTime(). They are still used in ghc-internal. Future directions: export the new ones from ghc-internal and base, and provide clock precision functions. Provide more clocks, like coarse ones: faster but less precise. - - - - - 27 changed files: - .gitlab/generate-ci/gen_ci.hs - .gitlab/jobs.yaml - libraries/ghc-internal/include/HsBase.h - + rts/GetTime.c - rts/GetTime.h - rts/posix/Clock.h → rts/OSStats.h - rts/RtsStartup.c - rts/RtsUtils.c - rts/Stats.c - rts/configure.ac - rts/eventlog/EventLog.c - rts/include/rts/GetTime.h - rts/include/rts/Time.h - rts/posix/GetTime.c - + rts/posix/OSStats.c - rts/posix/Poll.c - rts/posix/Select.c - rts/posix/SelectBis.c - rts/posix/Ticker.c - rts/posix/Timeout.c - rts/rts.cabal - rts/sm/GC.c - rts/wasm/GetTime.c - + rts/wasm/OSStats.c - rts/win32/GetTime.c - + rts/win32/OSStats.c - testsuite/tests/rts/TimeoutQueue.c Changes: ===================================== .gitlab/generate-ci/gen_ci.hs ===================================== @@ -476,8 +476,6 @@ opsysVariables AArch64 (Darwin {}) = mconcat opsysVariables Amd64 (Darwin {}) = mconcat [ "NIX_SYSTEM" =: "x86_64-darwin" , "MACOSX_DEPLOYMENT_TARGET" =: "11.0" - -- Only Sierra and onwards supports clock_gettime. See #12858 - , "ac_cv_func_clock_gettime" =: "no" -- Only newer OS Xs support utimensat. See #17895 , "ac_cv_func_utimensat" =: "no" -- Only newer OS Xs support futimens. See #22938 ===================================== .gitlab/jobs.yaml ===================================== @@ -3232,7 +3232,6 @@ "TEST_ENV": "x86_64-darwin-validate", "TEST_WAYS": "", "XZ_OPT": "-9", - "ac_cv_func_clock_gettime": "no", "ac_cv_func_futimens": "no", "ac_cv_func_utimensat": "no" } @@ -3299,7 +3298,6 @@ "TEST_ENV": "x86_64-darwin-validate", "TEST_WAYS": "", "XZ_OPT": "-9", - "ac_cv_func_clock_gettime": "no", "ac_cv_func_futimens": "no", "ac_cv_func_utimensat": "no" } @@ -8902,7 +8900,6 @@ "TEST_ENV": "x86_64-darwin-release", "TEST_WAYS": "", "XZ_OPT": "-9", - "ac_cv_func_clock_gettime": "no", "ac_cv_func_futimens": "no", "ac_cv_func_utimensat": "no" } @@ -8970,7 +8967,6 @@ "TEST_ENV": "x86_64-darwin-release", "TEST_WAYS": "", "XZ_OPT": "-9", - "ac_cv_func_clock_gettime": "no", "ac_cv_func_futimens": "no", "ac_cv_func_utimensat": "no" } @@ -11086,7 +11082,6 @@ "RUNTEST_ARGS": "", "TEST_ENV": "x86_64-darwin-validate", "TEST_WAYS": "", - "ac_cv_func_clock_gettime": "no", "ac_cv_func_futimens": "no", "ac_cv_func_utimensat": "no" } @@ -11152,7 +11147,6 @@ "RUNTEST_ARGS": "", "TEST_ENV": "x86_64-darwin-validate", "TEST_WAYS": "", - "ac_cv_func_clock_gettime": "no", "ac_cv_func_futimens": "no", "ac_cv_func_utimensat": "no" } ===================================== libraries/ghc-internal/include/HsBase.h ===================================== @@ -98,16 +98,6 @@ #elif HAVE_STDINT_H # include <stdint.h> #endif -#if defined(HAVE_CLOCK_GETTIME) -# if defined(_POSIX_MONOTONIC_CLOCK) -# define CLOCK_ID CLOCK_MONOTONIC -# else -# define CLOCK_ID CLOCK_REALTIME -# endif -#elif defined(darwin_HOST_OS) -# include <mach/mach.h> -# include <mach/mach_time.h> -#endif #if !defined(_WIN32) # if HAVE_SYS_RESOURCE_H ===================================== rts/GetTime.c ===================================== @@ -0,0 +1,27 @@ +/* ----------------------------------------------------------------------------- + * + * (c) The GHC Team, 1995-2009 + * + * Interface to the RTS time + * + * ---------------------------------------------------------------------------*/ + +#include "Rts.h" +#include "GetTime.h" + + +/* Exported alias for the internal getMonotonicTime(). + * Used in GHC.Internal.Clock + */ +StgWord64 getMonotonicNSec(void) +{ + return TimeToNS(getMonotonicTime()); +} + +/* Exported alias for the internal getMonotonicTime(). + * Used in ghc-internal/cbits/inputReady.c + */ +Time getProcessElapsedTime(void) +{ + return getMonotonicTime(); +} ===================================== rts/GetTime.h ===================================== @@ -4,24 +4,33 @@ * * Machine-independent interface to time measurement * + * See also the public functions includes/rts/GetTime.h * ---------------------------------------------------------------------------*/ #pragma once #include "BeginPrivate.h" -void initializeTimer (void); - -Time getProcessCPUTime (void); -Time getCurrentThreadCPUTime (void); -void getProcessTimes (Time *user, Time *elapsed); +/* Get the current time in a monotonic clock. + * + * The time is represented as nanoseconds since an arbitrary epoch. + * + * This is a high precision clock (on most platforms), but not necessarily + * nanosecond precision. + */ +Time getMonotonicTime(void); -/* Get the current date and time. - Uses seconds since the Unix epoch, plus nanoseconds +/* Get the current wall clock time. + * + * The time is represented as nanoseconds since the Unix epoch + * (1970-01-01 00:00). + * + * This is a high precision clock (on most platforms), but not necessarily + * nanosecond precision. */ -void getUnixEpochTime (StgWord64 *sec, StgWord32 *nsec); +Time getWallClockTime(void); -// Not strictly timing, but related -W_ getPageFaults (void); +Time getProcessCPUTime(void); +Time getCurrentThreadCPUTime(void); #include "EndPrivate.h" ===================================== rts/posix/Clock.h → rts/OSStats.h ===================================== @@ -1,30 +1,19 @@ /* ----------------------------------------------------------------------------- * - * (c) The GHC Team, 2012 + * (c) The GHC Team 2005 * - * Posix monotonic clock + * Machine-independent interface to process statistics * * ---------------------------------------------------------------------------*/ #pragma once -#if defined(HAVE_UNISTD_H) -# include <unistd.h> -#endif +#include "BeginPrivate.h" -#include <time.h> - -#if defined(HAVE_SYS_TIME_H) -# include <sys/time.h> -#endif +/* Count of the number of "major" page faults (since process start). + * + * In practice, always 0 for Win32 and wasm. + */ +long getPageFaults(void); -#if defined(HAVE_CLOCK_GETTIME) -# if defined(_POSIX_MONOTONIC_CLOCK) -# define CLOCK_ID CLOCK_MONOTONIC -# else -# define CLOCK_ID CLOCK_REALTIME -# endif -#elif defined(darwin_HOST_OS) -# include <mach/mach.h> -# include <mach/mach_time.h> -#endif +#include "EndPrivate.h" ===================================== rts/RtsStartup.c ===================================== @@ -360,9 +360,6 @@ hs_init_ghc(int *argc, char **argv[], RtsConfig rts_config) /* Initialise the stats department, phase 0 */ initStats0(); - /* Initialize system timer before starting to collect stats */ - initializeTimer(); - /* Next we do is grab the start time...just in case we're * collecting timing statistics. */ ===================================== rts/RtsUtils.c ===================================== @@ -31,10 +31,6 @@ extern char *ctime_r(const time_t *, char *); #include <fcntl.h> #endif -#if defined(HAVE_GETTIMEOFDAY) -#include <sys/time.h> -#endif - #include <stdlib.h> #include <string.h> #include <stdarg.h> @@ -207,31 +203,6 @@ exitHeapOverflow(void) stg_exit(EXIT_HEAPOVERFLOW); } -/* ----------------------------------------------------------------------------- - Sleep for the given period of time. - -------------------------------------------------------------------------- */ - -/* Returns -1 on failure but handles EINTR internally. On Windows this will - * only have millisecond precision. */ -int rtsSleep(Time t) -{ -#if defined(_WIN32) - // N.B. we can't use nanosleep on Windows as it would incur a pthreads - // dependency. See #18272. - Sleep(TimeToMS(t)); - return 0; -#else - struct timespec req; - req.tv_sec = TimeToSeconds(t); - req.tv_nsec = TimeToNS(t - req.tv_sec * TIME_RESOLUTION); - int ret; - do { - ret = nanosleep(&req, &req); - } while (ret == -1 && errno == EINTR); - return ret; -#endif /* _WIN32 */ -} - /* ----------------------------------------------------------------------------- Get the current time as a string. Used in profiling reports. -------------------------------------------------------------------------- */ ===================================== rts/Stats.c ===================================== @@ -15,6 +15,7 @@ #include "Stats.h" #include "Profiling.h" #include "GetTime.h" +#include "OSStats.h" #include "sm/Storage.h" #include "sm/GCThread.h" #include "sm/BlockAlloc.h" @@ -79,7 +80,13 @@ static void statsClose( void ); Time stat_getElapsedTime(void) { - return getProcessElapsedTime() - start_init_elapsed; + return getMonotonicTime() - start_init_elapsed; +} + +static void getProcessTimes(Time *user, Time *elapsed) +{ + *user = getProcessCPUTime(); + *elapsed = getMonotonicTime(); } /* --------------------------------------------------------------------------- @@ -294,7 +301,7 @@ stat_endExit(void) void stat_startGCSync (gc_thread *gct) { - gct->gc_sync_start_elapsed = getProcessElapsedTime(); + gct->gc_sync_start_elapsed = getMonotonicTime(); } void @@ -302,7 +309,7 @@ stat_startNonmovingGc (void) { ACQUIRE_LOCK(&stats_mutex); start_nonmoving_gc_cpu = getCurrentThreadCPUTime(); - start_nonmoving_gc_elapsed = getProcessElapsedTime(); + start_nonmoving_gc_elapsed = getMonotonicTime(); RELEASE_LOCK(&stats_mutex); } @@ -310,7 +317,7 @@ void stat_endNonmovingGc (void) { Time cpu = getCurrentThreadCPUTime(); - Time elapsed = getProcessElapsedTime(); + Time elapsed = getMonotonicTime(); ACQUIRE_LOCK(&stats_mutex); stats.gc.nonmoving_gc_elapsed_ns = elapsed - start_nonmoving_gc_elapsed; @@ -329,7 +336,7 @@ void stat_startNonmovingGcSync (void) { ACQUIRE_LOCK(&stats_mutex); - start_nonmoving_gc_sync_elapsed = getProcessElapsedTime(); + start_nonmoving_gc_sync_elapsed = getMonotonicTime(); RELEASE_LOCK(&stats_mutex); traceConcSyncBegin(); } @@ -337,7 +344,7 @@ stat_startNonmovingGcSync (void) void stat_endNonmovingGcSync (void) { - Time end_elapsed = getProcessElapsedTime(); + Time end_elapsed = getMonotonicTime(); ACQUIRE_LOCK(&stats_mutex); stats.gc.nonmoving_gc_sync_elapsed_ns = end_elapsed - start_nonmoving_gc_sync_elapsed; stats.nonmoving_gc_sync_elapsed_ns += stats.gc.nonmoving_gc_sync_elapsed_ns; @@ -435,7 +442,7 @@ stat_startGC (Capability *cap, gc_thread *gct) gct->gc_start_cpu = getCurrentThreadCPUTime(); } - gct->gc_start_elapsed = getProcessElapsedTime(); + gct->gc_start_elapsed = getMonotonicTime(); #if !defined(THREADED_RTS) // Non-threaded RTS has no sync phase. Initializing in this way makes the // calculated statistics correctly read zero. ===================================== rts/configure.ac ===================================== @@ -202,8 +202,11 @@ fi FP_MUSTTAIL -dnl ** check for librt -AC_CHECK_FUNCS(clock_gettime timer_settime) +dnl ** We now require clock_gettime for our monotonic clock. +if test "$ghc_host_os" != "mingw32" ; then + AC_CHECK_FUNCS([clock_gettime], [], + AC_MSG_ERROR([The POSIX.1-2008 function 'clock_gettime' is required but is not available])) +fi dnl ** check for Apple's "interesting" long double compatibility scheme AC_MSG_CHECKING(for printf\$LDBLStub) ===================================== rts/eventlog/EventLog.c ===================================== @@ -812,10 +812,6 @@ void postCapsetVecEvent (EventTypeNum tag, void postWallClockTime (EventCapsetID capset) { - StgWord64 ts; - StgWord64 sec; - StgWord32 nsec; - ACQUIRE_LOCK_ALWAYS(&eventBufMutex); /* The EVENT_WALL_CLOCK_TIME event is intended to allow programs @@ -834,8 +830,12 @@ void postWallClockTime (EventCapsetID capset) difference we just call them very close together. */ - getUnixEpochTime(&sec, &nsec); /* Get the wall clock time */ - ts = time_ns(); /* Get the eventlog timestamp */ + Time now = getWallClockTime(); /* Get the wall clock time */ + StgWord64 ts = time_ns(); /* Get the eventlog timestamp */ + + StgWord64 sec = now / TIME_RESOLUTION; + StgWord32 nsec = now % TIME_RESOLUTION; + ensureRoomForEvent(&eventBuf, EVENT_WALL_CLOCK_TIME); /* Normally we'd call postEventHeader(), but that generates its own ===================================== rts/include/rts/GetTime.h ===================================== @@ -13,4 +13,24 @@ #pragma once -StgWord64 getMonotonicNSec (void); +/* The monotonic time source used within the RTS. + * + * Note that this uses StgWord64, rather than Time which is int64_t . + */ +StgWord64 getMonotonicNSec(void); + +/* The monotonic time source used within the RTS. + * + * There is no good reason (except history) that we have both this and + * getMonotonicNSec. + */ +Time getProcessElapsedTime(void); + + +/* It might be nice to tidy this up and export monotonic and wall clock time + * and precision and bind them in ghc-internal. They should probably all + * use int64_t / CInt64. + * + * The internal functions are getMonotonicTime() and getWallClockTime(). + * These would be better candidates for export. + */ ===================================== rts/include/rts/Time.h ===================================== @@ -41,5 +41,3 @@ INLINE_HEADER Time fsecondsToTime (double t) { return (Time)(t * TIME_RESOLUTION); } - -Time getProcessElapsedTime (void); ===================================== rts/posix/GetTime.c ===================================== @@ -6,252 +6,60 @@ * * ---------------------------------------------------------------------------*/ -// Not POSIX, due to use of ru_majflt in getPageFaults() -// #include "rts/PosixSource.h" - +#include "rts/PosixSource.h" #include "Rts.h" #include "GetTime.h" -#include "Clock.h" -#if defined(HAVE_SYS_RESOURCE_H) -# include <sys/resource.h> -#endif - -#if defined(HAVE_SYS_TIMES_H) -# include <sys/times.h> -#endif - -#if ! (defined(HAVE_GETRUSAGE) || defined(HAVE_TIMES)) -#error No implementation for getProcessCPUTime() available. -#endif - -#if defined(darwin_HOST_OS) -#include <mach/mach_time.h> -#include <mach/mach_init.h> -#include <mach/thread_act.h> -#include <mach/mach_port.h> -#endif +#include <unistd.h> +#include <time.h> #if defined(solaris2_HOST_OS) #include <sys/time.h> #endif -#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_GETRUSAGE) -// we'll implement getProcessCPUTime() and getProcessElapsedTime() -// separately, using getrusage() and gettimeofday() respectively -#if defined(darwin_HOST_OS) -static uint64_t timer_scaling_factor_numer = 0; -static uint64_t timer_scaling_factor_denom = 0; +#if !defined(HAVE_CLOCK_GETTIME) +#error We reqire clock_gettime. This should have been checked in configure.ac +#elif !defined(_POSIX_MONOTONIC_CLOCK) +#warning _POSIX_MONOTONIC_CLOCK not defined, which is likely to be a problem. #endif -void initializeTimer(void) -{ -#if defined(darwin_HOST_OS) - mach_timebase_info_data_t info; - (void) mach_timebase_info(&info); - timer_scaling_factor_numer = (uint64_t)info.numer; - timer_scaling_factor_denom = (uint64_t)info.denom; -#endif -} - -#if defined(HAVE_CLOCK_GETTIME) static Time getClockTime(clockid_t clock) { struct timespec ts; int res = clock_gettime(clock, &ts); - if (res == 0) { + if (RTS_LIKELY(res == 0)) { return SecondsToTime(ts.tv_sec) + NSToTime(ts.tv_nsec); } else { sysErrorBelch("clock_gettime"); stg_exit(EXIT_FAILURE); } } -#endif Time getCurrentThreadCPUTime(void) { - // N.B. Since macOS Catalina, Darwin supports clock_gettime but does not - // support clock_getcpuclockid. Hence we prefer to use the Darwin-specific - // path on Darwin, even if clock_gettime is available. -#if defined(darwin_HOST_OS) - thread_basic_info_data_t info = { }; - mach_msg_type_number_t info_count = THREAD_BASIC_INFO_COUNT; - kern_return_t kern_err = thread_info(mach_thread_self(), THREAD_BASIC_INFO, - (thread_info_t) &info, &info_count); - if (kern_err == KERN_SUCCESS) { - return SecondsToTime(info.user_time.seconds) + USToTime(info.user_time.microseconds); - } else { - sysErrorBelch("getThreadCPUTime"); - stg_exit(EXIT_FAILURE); - } -#elif defined(solaris2_HOST_OS) +#if defined(solaris2_HOST_OS) // On OpenSolaris derivatives, the constant CLOCK_THREAD_CPUTIME_ID is // defined in a system header but it isn't actually usable. clock_gettime(2) // always returns EINVAL. Use solaris-specific gethrvtime(3) as an // alternative. return NSToTime(gethrvtime()); -#elif defined(HAVE_CLOCK_GETTIME) && \ - defined(CLOCK_PROCESS_CPUTIME_ID) && \ - defined(HAVE_SYSCONF) - static bool have_checked_usability = false; - // The RELAXED operation is fine here as it's okay if we do the check below - // more than once. - if (!RELAXED_LOAD(&have_checked_usability)) { - // The Linux clock_getres(2) manpage claims that some early versions of - // Linux will return values which are uninterpretable in the presence - // of migration across CPUs. They claim that clock_getcpuclockid(0) - // will return ENOENT in this case. Check this. - clockid_t clkid; - if (clock_getcpuclockid(0, &clkid)) { - sysErrorBelch("getCurrentThreadCPUTime: no supported"); - stg_exit(EXIT_FAILURE); - } - RELAXED_STORE(&have_checked_usability, true); - } - return getClockTime(CLOCK_THREAD_CPUTIME_ID); #else -#error I know of no means to find the CPU time of current thread on this platform. -#endif -} - -Time getProcessCPUTime(void) -{ -#if !defined(BE_CONSERVATIVE) && \ - defined(HAVE_CLOCK_GETTIME) && \ - defined(_SC_CPUTIME) && \ - defined(CLOCK_PROCESS_CPUTIME_ID) && \ - defined(HAVE_SYSCONF) - static int checked_sysconf = 0; - static int sysconf_result = 0; - - if (!checked_sysconf) { - sysconf_result = sysconf(_SC_CPUTIME); - checked_sysconf = 1; - } - if (sysconf_result != -1) { - return getClockTime(CLOCK_PROCESS_CPUTIME_ID); - } -#endif - - // fallback to getrusage - { - struct rusage t; - getrusage(RUSAGE_SELF, &t); - return SecondsToTime(t.ru_utime.tv_sec + t.ru_stime.tv_sec) - + USToTime(t.ru_utime.tv_usec + t.ru_stime.tv_usec); - } -} - -StgWord64 getMonotonicNSec(void) -{ -#if defined(HAVE_CLOCK_GETTIME) - return getClockTime(CLOCK_ID); - -#elif defined(darwin_HOST_OS) - - uint64_t time = mach_absolute_time(); - return (time * timer_scaling_factor_numer) / timer_scaling_factor_denom; - -#else // use gettimeofday() - - struct timeval tv; - - if (gettimeofday(&tv, (struct timezone *) NULL) != 0) { - debugBlech("getMonotonicNSec: gettimeofday failed: %s", strerror(errno)); - }; - return (StgWord64)tv.tv_sec * 1000000000 + - (StgWord64)tv.tv_usec * 1000; - + return getClockTime(CLOCK_THREAD_CPUTIME_ID); #endif } -Time getProcessElapsedTime(void) -{ - return NSToTime(getMonotonicNSec()); -} - -void getProcessTimes(Time *user, Time *elapsed) -{ - *user = getProcessCPUTime(); - *elapsed = getProcessElapsedTime(); -} - -#elif defined(HAVE_TIMES) - -// we'll use the old times() API. - Time getProcessCPUTime(void) { - Time user, elapsed; - getProcessTimes(&user,&elapsed); - return user; -} - -Time getProcessElapsedTime(void) -{ - Time user, elapsed; - getProcessTimes(&user,&elapsed); - return elapsed; -} - -void getProcessTimes(Time *user, Time *elapsed) -{ - static uint32_t ClockFreq = 0; - - if (ClockFreq == 0) { -#if defined(HAVE_SYSCONF) - long ticks; - ticks = sysconf(_SC_CLK_TCK); - if ( ticks == -1 ) { - sysErrorBelch("sysconf"); - stg_exit(EXIT_FAILURE); - } - ClockFreq = ticks; -#elif defined(CLK_TCK) /* defined by POSIX */ - ClockFreq = CLK_TCK; -#elif defined(HZ) - ClockFreq = HZ; -#elif defined(CLOCKS_PER_SEC) - ClockFreq = CLOCKS_PER_SEC; -#else - errorBelch("can't get clock resolution"); - stg_exit(EXIT_FAILURE); -#endif - } - - struct tms t; - clock_t r = times(&t); - *user = SecondsToTime(t.tms_utime) / ClockFreq; - *elapsed = SecondsToTime(r) / ClockFreq; + return getClockTime(CLOCK_PROCESS_CPUTIME_ID); } -#endif // HAVE_TIMES - -void getUnixEpochTime(StgWord64 *sec, StgWord32 *nsec) +Time getMonotonicTime(void) { -#if defined(HAVE_GETTIMEOFDAY) - struct timeval tv; - gettimeofday(&tv, (struct timezone *) NULL); - *sec = tv.tv_sec; - *nsec = tv.tv_usec * 1000; -#else - /* Sigh, fall back to second resolution. */ - time_t t; - time(&t); - *sec = t; - *nsec = 0; -#endif + return getClockTime(CLOCK_MONOTONIC); } -W_ -getPageFaults(void) +Time getWallClockTime(void) { -#if !defined(HAVE_GETRUSAGE) || defined(haiku_HOST_OS) - return 0; -#else - struct rusage t; - getrusage(RUSAGE_SELF, &t); - return(t.ru_majflt); -#endif + return getClockTime(CLOCK_REALTIME); } ===================================== rts/posix/OSStats.c ===================================== @@ -0,0 +1,30 @@ +/* ----------------------------------------------------------------------------- + * + * (c) The GHC Team 2005 + * + * Machine-dependent process statistics functions + * + * ---------------------------------------------------------------------------*/ + +// Not POSIX, due to use of ru_majflt in getPageFaults() +// #include "rts/PosixSource.h" + +#include "Rts.h" +#include "OSStats.h" + +#include <unistd.h> + +#if defined(HAVE_SYS_RESOURCE_H) +# include <sys/resource.h> +#endif + +long getPageFaults(void) +{ +#if !defined(HAVE_GETRUSAGE) || defined(haiku_HOST_OS) + return 0; +#else + struct rusage t; + getrusage(RUSAGE_SELF, &t); + return(t.ru_majflt); +#endif +} ===================================== rts/posix/Poll.c ===================================== @@ -370,7 +370,7 @@ void pollCompletedTimeoutsOrIOPoll(CapIOManager *iomgr) ASSERT(iomgr->aiop_poll_table == iomgr->full_poll_table+1); if (!isEmptyTimeoutQueue(iomgr->timeout_queue)) { - Time now = getProcessElapsedTime(); + Time now = getMonotonicTime(); processTimeoutCompletions(iomgr, now); } @@ -440,7 +440,7 @@ bool awaitCompletedTimeoutsOrIOPoll(CapIOManager *iomgr) ASSERT(!isEmptyTimeoutQueue(iomgr->timeout_queue) || !isEmptyClosureTable(&iomgr->aiop_table)); - Time now = getProcessElapsedTime(); + Time now = getMonotonicTime(); processTimeoutCompletions(iomgr, now); /* If we didn't wake any threads due to expiring timeouts, then we need ===================================== rts/posix/Select.c ===================================== @@ -34,8 +34,6 @@ #include <errno.h> #include <string.h> -#include "Clock.h" - #if defined(IOMGR_ENABLED_SELECT) // The target time for a threadDelay is stored in a one-word quantity @@ -93,7 +91,7 @@ void interruptIOManagerSelect(CapIOManager *iomgr) */ static LowResTime getLowResTimeOfDay(void) { - return TimeToLowResTimeRoundDown(getProcessElapsedTime()); + return TimeToLowResTimeRoundDown(getMonotonicTime()); } /* @@ -102,7 +100,7 @@ static LowResTime getLowResTimeOfDay(void) LowResTime getDelayTarget (HsInt us) { Time elapsed; - elapsed = getProcessElapsedTime(); + elapsed = getMonotonicTime(); // If the desired target would be larger than the maximum Time, // default to the maximum Time. (#7087) ===================================== rts/posix/SelectBis.c ===================================== @@ -355,7 +355,7 @@ static bool processIOCompletions(CapIOManager *iomgr, int ncompletions) void pollCompletedTimeoutsOrIOSelectBis(CapIOManager *iomgr) { if (!isEmptyTimeoutQueue(iomgr->timeout_queue)) { - Time now = getProcessElapsedTime(); + Time now = getMonotonicTime(); processTimeoutCompletions(iomgr, now); } @@ -406,7 +406,7 @@ bool awaitCompletedTimeoutsOrIOSelectBis(CapIOManager *iomgr) ASSERT(!isEmptyTimeoutQueue(iomgr->timeout_queue) || !isEmptyClosureTable(&iomgr->aiop_table)); - Time now = getProcessElapsedTime(); + Time now = getMonotonicTime(); processTimeoutCompletions(iomgr, now); /* If we didn't wake any threads due to expiring timeouts, then we need ===================================== rts/posix/Ticker.c ===================================== @@ -64,9 +64,11 @@ #include "RtsUtils.h" #include "Proftimer.h" #include "Schedule.h" -#include "posix/Clock.h" #include "posix/FdWakeup.h" +#include <unistd.h> +#include <time.h> + #if defined(HAVE_DECL_PPOLL) && HAVE_DECL_PPOLL == 1 /* We prefer the ppoll() function if available since it allows sanely waiting * on a single fd with precise timeouts (nanosecond precision). It is not in @@ -85,11 +87,6 @@ #include <sys/select.h> #endif -#include <time.h> -#if HAVE_SYS_TIME_H -# include <sys/time.h> -#endif - #if defined(HAVE_SIGNAL_H) # include <signal.h> #endif @@ -100,7 +97,6 @@ #if defined(HAVE_PTHREAD_NP_H) #include <pthread_np.h> #endif -#include <unistd.h> #include <fcntl.h> ===================================== rts/posix/Timeout.c ===================================== @@ -30,7 +30,7 @@ bool syncDelayTimeout(CapIOManager *iomgr, StgTSO *tso, HsInt us_delay) { - Time now = getProcessElapsedTime(); + Time now = getMonotonicTime(); Time target; /* If the desired target would be larger than the maximum Time, ===================================== rts/rts.cabal ===================================== @@ -413,6 +413,7 @@ library Disassembler.c FileLock.c ForeignExports.c + GetTime.c Globals.c Hash.c Heap.c @@ -553,6 +554,7 @@ library win32/GetTime.c win32/MIOManager.c win32/OSMem.c + win32/OSStats.c win32/OSThreads.c win32/ThrIOManager.c win32/Ticker.c @@ -564,6 +566,7 @@ library c-sources: wasm/StgRun.c wasm/GetTime.c wasm/OSMem.c + wasm/OSStats.c wasm/OSThreads.c wasm/JSFFI.c wasm/JSFFIGlobals.c @@ -579,6 +582,7 @@ library posix/GetTime.c posix/Ticker.c posix/OSMem.c + posix/OSStats.c posix/OSThreads.c posix/FdWakeup.c posix/MIO.c ===================================== rts/sm/GC.c ===================================== @@ -1518,7 +1518,7 @@ waitForGcThreads (Capability *cap, bool idle_cap[]) uint32_t i, cur_n_gc_entered; Time t0, t1, t2; - t0 = t1 = t2 = getProcessElapsedTime(); + t0 = t1 = t2 = getMonotonicTime(); for(i = 0; i < getNumCapabilities(); ++i) { if (i == me || idle_cap[i]) { @@ -1542,7 +1542,7 @@ waitForGcThreads (Capability *cap, bool idle_cap[]) // this 1ms timeout is not well justified. It's the shortest timeout we // can use on windows. It seems to work well for me. timedWaitCondition(&gc_entry_arrived_cv, &gc_entry_mutex, USToTime(1000)); - t2 = getProcessElapsedTime(); + t2 = getMonotonicTime(); if (RtsFlags.GcFlags.longGCSync != 0 && t2 - t1 > RtsFlags.GcFlags.longGCSync) { // best not to hold the mutex while we call a hook function ===================================== rts/wasm/GetTime.c ===================================== @@ -6,19 +6,13 @@ * * ---------------------------------------------------------------------------*/ -// Not POSIX, due to use of ru_majflt in getPageFaults() -// #include "rts/PosixSource.h" - +#include "rts/PosixSource.h" #include "Rts.h" #include "GetTime.h" #include <time.h> #include <sys/time.h> -void initializeTimer(void) -{ -} - static Time getClockTime(clockid_t clock) { struct timespec ts; @@ -41,32 +35,14 @@ Time getProcessCPUTime(void) return getClockTime(CLOCK_MONOTONIC); } -StgWord64 getMonotonicNSec(void) +Time getMonotonicTime(void) { return getClockTime(CLOCK_MONOTONIC); } -Time getProcessElapsedTime(void) -{ - return NSToTime(getMonotonicNSec()); -} - -void getProcessTimes(Time *user, Time *elapsed) -{ - *user = getProcessCPUTime(); - *elapsed = getProcessElapsedTime(); -} - -void getUnixEpochTime(StgWord64 *sec, StgWord32 *nsec) +Time getWallClockTime(void) { struct timeval tv; gettimeofday(&tv, (struct timezone *) NULL); - *sec = tv.tv_sec; - *nsec = tv.tv_usec * 1000; -} - -W_ -getPageFaults(void) -{ - return 0; + return SecondsToTime(tv.tv_sec) + USToTime(tv.tv_usec); } ===================================== rts/wasm/OSStats.c ===================================== @@ -0,0 +1,15 @@ +/* ----------------------------------------------------------------------------- + * + * (c) The GHC Team 2005 + * + * Machine-dependent process statistics functions + * + * ---------------------------------------------------------------------------*/ + +#include "Rts.h" +#include "OSStats.h" + +long getPageFaults(void) +{ + return 0; +} ===================================== rts/win32/GetTime.c ===================================== @@ -15,8 +15,7 @@ /* Convert FILETIMEs into secs */ -static inline Time -fileTimeToRtsTime(FILETIME ft) +static inline Time fileTimeToRtsTime(FILETIME ft) { Time t; t = ((Time)ft.dwHighDateTime << 32) | ft.dwLowDateTime; @@ -25,15 +24,7 @@ fileTimeToRtsTime(FILETIME ft) return t; } -void -getProcessTimes(Time *user, Time *elapsed) -{ - *user = getProcessCPUTime(); - *elapsed = getProcessElapsedTime(); -} - -Time -getCurrentThreadCPUTime(void) +Time getCurrentThreadCPUTime(void) { FILETIME creationTime, exitTime, userTime, kernelTime = {0,0}; @@ -46,8 +37,7 @@ getCurrentThreadCPUTime(void) return fileTimeToRtsTime(userTime); } -Time -getProcessCPUTime(void) +Time getProcessCPUTime(void) { FILETIME creationTime, exitTime, userTime, kernelTime = {0,0}; @@ -59,108 +49,57 @@ getProcessCPUTime(void) return fileTimeToRtsTime(userTime); } -// Number of ticks per second used by the QueryPerformanceFrequency -// implementation, represented by a 64-bit union type. -static LARGE_INTEGER qpc_frequency = {.QuadPart = 0}; - -// Initialize qpc_frequency. This function should be called before any call to -// getMonotonicNSec. If QPC is not supported on this system, qpc_frequency is -// set to 0. -void initializeTimer(void) +Time getMonotonicTime(void) { - BOOL qpc_supported = QueryPerformanceFrequency(&qpc_frequency); - if (!qpc_supported) - { - qpc_frequency.QuadPart = 0; + // https://learn.microsoft.com/en-us/windows/win32/sysinfo/acquiring-high-resol... + // The advice there is use QueryPerformanceCounter, and that this is now + // always supported in Windows XP and later, and reliable from Vista. + + // Number of ticks per second, provided by QueryPerformanceFrequency + static Time ticks_per_sec = 0; + + // Initialize ticks_per_sec on the first call. It should not matter if two + // threads race to do this. The result should be the same. + if (RTS_UNLIKELY(RELAXED_LOAD_ALWAYS(&ticks_per_sec) == 0)) { + LARGE_INTEGER qpc_frequency; // a 64-bit union type + if (QueryPerformanceFrequency(&qpc_frequency)) { + RELAXED_STORE_ALWAYS(&ticks_per_sec, qpc_frequency.QuadPart); + } else { + // This should be impossible now. + sysErrorBelch("getMonotonicTime: high res timestamps not available"); + stg_exit(EXIT_FAILURE); + } } -} - -HsWord64 -getMonotonicNSec(void) -{ - if (qpc_frequency.QuadPart) - { - // system_time is a 64-bit union type used to represent the - // tick count returned by QueryPerformanceCounter - LARGE_INTEGER system_time; - - // get the tick count. - QueryPerformanceCounter(&system_time); - - // compute elapsed seconds as double - double secs = (double)system_time.QuadPart / - (double)qpc_frequency.QuadPart; - // return elapsed time in nanoseconds - return (HsWord64)(secs * 1e9); - } - else // fallback to GetTickCount - { - // TODO: Remove this code path, it cannot be taken because - // `QueryPerformanceFrequency` cannot fail on Windows >= XP - // and GHC no longer supports Windows <= XP. - // See https://gitlab.haskell.org/ghc/ghc/issues/14233 - - // NOTE: GetTickCount is a 32-bit millisecond value, so it wraps around - // every 49 days. - DWORD count = GetTickCount(); - - // getTickCount is in milliseconds, so multiply it by 1000000 to get - // nanoseconds. - return (HsWord64)count * 1000000; - } -} + // Get the tick count. + LARGE_INTEGER tick_count; + QueryPerformanceCounter(&tick_count); -Time -getProcessElapsedTime(void) -{ - return NSToTime(getMonotonicNSec()); + // Compute elapsed time in nanoseconds. If avoiding float, we must multiply + // by nanoseconds first (1e9) and then divide by ticks per sec. The + // intermediate result can overflow a 64bit integer. So we use 128bit. + return ((__uint128_t)tick_count.QuadPart * (__uint128_t)1000000000ull) + / (__uint128_t)ticks_per_sec; } -void -getUnixEpochTime(StgWord64 *sec, StgWord32 *nsec) +Time getWallClockTime(void) { - /* Windows has a bunch of time APIs but none that directly give - us unix epoch time, so we have to do a little dance. */ - - SYSTEMTIME systime; - FILETIME filetime; - ULARGE_INTEGER unixtime; - - /* Windows SYSTEMTIME is a big struct with fields for - year, month, day, hour, minute, second, millisecond. */ - GetSystemTime(&systime); /* Windows FILETIME timestamps use an epoch-based time, using a 64bit unsigned word. The time is measured in units of 100 nanoseconds since an epoch of 1601. */ - SystemTimeToFileTime(&systime, &filetime); + FILETIME filetime; + GetSystemTimePreciseAsFileTime(&filetime); /* FILETIME isn't directly a 64bit word, but a struct with a pair of 32bit words, so we have to convert via a ULARGE_INTEGER struct which is a handy union type */ + ULARGE_INTEGER unixtime; unixtime.LowPart = filetime.dwLowDateTime; unixtime.HighPart = filetime.dwHighDateTime; /* We have to do an epoch conversion, since FILETIME uses 1601 while we want unix epoch of 1970. In case you were wondering, there were 11,644,473,600 seconds between 1601 and 1970, then - multiply by 10^7 for units of 100 nanoseconds. */ - unixtime.QuadPart = unixtime.QuadPart - 116444736000000000ull; - - /* For the seconds part we use integer division by 10^7 */ - *sec = unixtime.QuadPart / 10000000ull; - - /* The remainder from integer division by 10^7 gives us - the sub-second component in units of 100 nanoseconds. - So for nanoseconds we just multiply by 100. - Note that nanoseconds always fits in a 32bit word */ - *nsec = ((unsigned long)(unixtime.QuadPart % 10000000ull)) * 100ul; -} - -W_ -getPageFaults(void) -{ - /* ToDo (on NT): better, get this via the performance data - that's stored in the registry. */ - return 0; + multiply by 100 for units of 100 nanoseconds. */ + return ((Time)unixtime.QuadPart - 116444736000000000ull) * 100ull; } ===================================== rts/win32/OSStats.c ===================================== @@ -0,0 +1,17 @@ +/* ----------------------------------------------------------------------------- + * + * (c) The GHC Team 2005 + * + * Machine-dependent process statistics functions + * + * ---------------------------------------------------------------------------*/ + +#include "Rts.h" +#include "OSStats.h" + +long getPageFaults(void) +{ + /* ToDo (on NT): better, get this via the performance data + that's stored in the registry. */ + return 0; +} ===================================== testsuite/tests/rts/TimeoutQueue.c ===================================== @@ -227,7 +227,6 @@ int main_bench (bool showtiming) StgTimeoutQueue *root = EMPTY; Time before, after; - initializeTimer(); /* Init */ StgTimeoutQueue *elems = calloc(N, sizeof(StgTimeoutQueue)); View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/2e3e4171c62f0ab60cf39185022db7e... -- View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/2e3e4171c62f0ab60cf39185022db7e... You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
participants (1)
-
Duncan Coutts (@dcoutts)