Duncan Coutts pushed to branch wip/dcoutts/posix-time at Glasgow Haskell Compiler / GHC Commits: af5f4fc8 by Duncan Coutts at 2026-11-16T20:56:59+00:00 Improve win32 implementation of getMonotonicNSec We don't need the fallback GetTickCount method. Fixes #14233 - - - - - 4873d4f5 by Duncan Coutts at 2026-11-16T20:56:59+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. - - - - - 310d9b3c by Duncan Coutts at 2026-11-16T20:56:59+00:00 Remove initializeTimer It is now a no-op on all platforms. - - - - - 0c2d6a5c by Duncan Coutts at 2026-11-16T20:56:59+00:00 Refine the meaning of the main monotonic clock and add a high-res clock We now define the monotonic clock to prioritise accuracy, and to be steady: which implies it must count time while the system is suspended. In particular this means that on Linux we must use CLOCK_BOOTTIME. Since different use cases want different trade-offs (where such trade-offs are necessary on some platforms) we also add support for a high resolution clock. This is defined to be as precise as possible, but not necessarily steady or accurate over long timer periods. This is the appropriate choice for measuring the time of short-running actions. We don't get use this one, but will do in susbequent changes. - - - - - ddb48e75 by Duncan Coutts at 2026-11-16T20:56:59+00:00 Switch some RTS uses from getMonotonicTime to getHighResolutionTime Wherever we want to measure the duration of relatively short time intervals then we want getHighResolutionTime rather than getMonotonicTime. In particular this is appropriate for RTS stats, profiling and the eventlog timestamps. In practice this is hardly a change in behaviour compared to the prior implementation of getMonotonicNSec/getProcessElapsedTime. On Linux and FreeBSD it used CLOCK_MONOTONIC, and still does (or the more-or-less equivalent CLOCK_BOOTTIME on Linux). On macOS it used the low-level mach_absolute_time and now uses the equivalent CLOCK_UPTIME_RAW for getHighResolutionTime. While on Windows getHighResolutionTime uses QueryPerformanceCounter, the same as previously. - - - - - 284f4572 by Duncan Coutts at 2026-11-16T20:56:59+00:00 Add support for macOS non-standard clock_gettime_nsec_np It's a way to get what we want with fewer conversions, so plausibly faster. - - - - - c478085d by Duncan Coutts at 2026-11-16T20:56:59+00:00 Remove unused rtsSleep utility - - - - - fa788650 by Duncan Coutts at 2026-11-16T20:56:59+00:00 Add a changelog entry for the clock_gettime changes - - - - - 12 changed files: - + changelog.d/clock_gettime - rts/GetTime.h - rts/RtsStartup.c - rts/RtsUtils.c - rts/Stats.c - rts/configure.ac - rts/posix/Clock.h - rts/posix/GetTime.c - rts/sm/GC.c - rts/wasm/GetTime.c - rts/win32/GetTime.c - testsuite/tests/rts/TimeoutQueue.c Changes: ===================================== changelog.d/clock_gettime ===================================== @@ -0,0 +1,18 @@ +section: rts +synopsis: The RTS now uses the `clock_gettime` monotonic clock on all POSIX platforms. +issues: #28119 #14233 +mrs: !16968 +description: + Having a good monotonic clock source is vital for concurrent programming. + Historically platform APIs for high precision monotonic time have not been + widely available in a consistent standard form, and GHC was forced to depend + on a hodge podge of different APIs (some of which did not even provide + monotonic time). POSIX.1-2008 mandated the `clock_gettime` API, and this is + now old enough and widely supported enough that the RTS can now use this + with the `CLOCK_MONOTONIC` and `CLOCK_REALTIME` clocks for all of its internal + timing needs on all POSIX platforms. + + The compatibility implication is that some older POSIX platforms that do not + support the POSIX.1-2008 standard will no longer be supported. To the best of + our knowledge the main platforms impacted are versions of macOS prior to + version 10.12 (released 2016, EOL 2019). ===================================== rts/GetTime.h ===================================== @@ -11,18 +11,76 @@ #include "BeginPrivate.h" -void initializeTimer (void); +/* Note [Meaning of clocks] + * ~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Clock terminology + * + * 1. monotonic time: non-decreasing. This is for measuring intervals, not + * subject to time jumps (e.g. due to NTP or user fixing the time). + * 2. real / wall clock time: corresponding to real world UTC time. + * 3. CPU time: time spent by threads/processes running on a CPU. + * 4. steady clock: (following the C++11 library definition): the time + * between ticks of this clock is constant. In particular this implies it + * _does_ keep time even when the system is suspended/hibernated. Note that + * a wall clock must be steady, whereas a monotonic clock need not be. + * + * An ideal clock would be: + * 1. accurate: able to keep time over long periods; + * 2. precise: a high resolution of clock measurement; + * 3. fast: the time duration to measure the clock. + * + * Real clocks available on platforms must make compromises. + * + * We provide a choice of clocks that pick the best platform clocks given + * different priorities between these desires. + * + * 1. A monotonic, steady, accurate clock: getMonotonicTime + * 2. A precise monotonic clock: getHighResolutionTime + * 3. An accurate real time clock: getWallClockTime + * + * We could also (but do not currently) provide: + * 4. A fast monotonic clock (but not comparable to the accurate clock) + * 5. A fast real time clock (a less precise real time clock, and comparable) + * + * In general these clocks are _not_ comparable. The only ones that _could_ be + * comparable (if we were to need and provide them) are low res clocks that are + * (guaranteed) to be low resolution measures of the same clock. + */ -/* Get the current time in a monotonic clock. +/* Get the current time in a monotonic, steady, accurate clock. + * See Note [Meaning of clocks]. * * The time is represented as nanoseconds since an arbitrary epoch. + * + * This is the clock used for user timeouts like threadDelay. */ Time getMonotonicTime(void); -/* Get the current wall clock time. +/* Get the time in a monotonic, high resolution clock. + * See Note [Meaning of clocks]. + * + * This is intended to be the most high resolution / precise clock available on + * the platform. It is suitable for timing operations with maximum available + * precision. + * + * It is not necessarily accurate at keeping time over long time periods (i.e. + * may be subject to time drift). It is not necessarily steady: it may or may + * not include time while the system is suspend. + * + * This is the clock used for measuring timing of activities within the RTS: + * RTS stats, profiling and eventlog timestamps. + */ +Time getHighResolutionTime(void); + +/* Get the time in a real time, accurate clock. + * See Note [Meaning of clocks]. * * The time is represented as nanoseconds since the Unix epoch * (1970-01-01 00:00). + * + * This clock is not used much, but is emitted into eventlogs on start to + * enable matching the eventlog timestamps with wall clock time. */ Time getWallClockTime(void); ===================================== 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 ===================================== @@ -75,18 +75,22 @@ static void statsFlush( void ); static void statsClose( void ); /* ----------------------------------------------------------------------------- - Current elapsed time + Current time + + We use the high resolution clock, not the accurate steady clock. + This is for measuring how long things take over relatively short intervals. ------------------------------------------------------------------------- */ +/* Used for eventlog timestamps, and matching census->rtime */ Time stat_getElapsedTime(void) { - return getMonotonicTime() - start_init_elapsed; + return getHighResolutionTime() - start_init_elapsed; } static void getProcessTimes(Time *user, Time *elapsed) { *user = getProcessCPUTime(); - *elapsed = getMonotonicTime(); + *elapsed = getHighResolutionTime(); } /* --------------------------------------------------------------------------- @@ -301,7 +305,7 @@ stat_endExit(void) void stat_startGCSync (gc_thread *gct) { - gct->gc_sync_start_elapsed = getMonotonicTime(); + gct->gc_sync_start_elapsed = getHighResolutionTime(); } void @@ -309,7 +313,7 @@ stat_startNonmovingGc (void) { ACQUIRE_LOCK(&stats_mutex); start_nonmoving_gc_cpu = getCurrentThreadCPUTime(); - start_nonmoving_gc_elapsed = getMonotonicTime(); + start_nonmoving_gc_elapsed = getHighResolutionTime(); RELEASE_LOCK(&stats_mutex); } @@ -317,7 +321,7 @@ void stat_endNonmovingGc (void) { Time cpu = getCurrentThreadCPUTime(); - Time elapsed = getMonotonicTime(); + Time elapsed = getHighResolutionTime(); ACQUIRE_LOCK(&stats_mutex); stats.gc.nonmoving_gc_elapsed_ns = elapsed - start_nonmoving_gc_elapsed; @@ -336,7 +340,7 @@ void stat_startNonmovingGcSync (void) { ACQUIRE_LOCK(&stats_mutex); - start_nonmoving_gc_sync_elapsed = getMonotonicTime(); + start_nonmoving_gc_sync_elapsed = getHighResolutionTime(); RELEASE_LOCK(&stats_mutex); traceConcSyncBegin(); } @@ -344,7 +348,7 @@ stat_startNonmovingGcSync (void) void stat_endNonmovingGcSync (void) { - Time end_elapsed = getMonotonicTime(); + Time end_elapsed = getHighResolutionTime(); 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; @@ -451,7 +455,7 @@ stat_startGC (Capability *cap, gc_thread *gct) gct->gc_start_cpu = getCurrentThreadCPUTime(); } - gct->gc_start_elapsed = getMonotonicTime(); + gct->gc_start_elapsed = getHighResolutionTime(); #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 ===================================== @@ -206,6 +206,7 @@ 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])) + AC_CHECK_FUNCS([clock_gettime_nsec_np]) fi dnl ** check for Apple's "interesting" long double compatibility scheme ===================================== rts/posix/Clock.h ===================================== @@ -8,7 +8,43 @@ #pragma once + +#if defined(linux_HOST_OS) || defined(linux_android_HOST_OS) +/* On Linux the CLOCK_MONOTONIC does not count time while the machine is + * suspend. We have defined getMonotonicTime to be a steady clock (which does + * count time while suspend). So on Linux we use CLOCK_BOOTTIME: + * + * > A nonsettable system-wide clock that is identical to CLOCK_MONOTONIC, + * > except that it also includes any time that the system is suspended. + * + * The only downside is that there is no CLOCK_BOOTTIME_COARSE, only + * CLOCK_MONOTONIC_COARSE. + */ +#define RTS_CLOCK_MONOTONIC CLOCK_BOOTTIME + +#else +/* On (most?) other POSIX platforms the CLOCK_MONOTONIC counts time while the + * machine is suspend. In particular this is true on FreeBSD and macOS. + */ #define RTS_CLOCK_MONOTONIC CLOCK_MONOTONIC +#endif + + +#if defined(darwin_HOST_OS) || defined(ios_HOST_OS) +/* On macOS CLOCK_UPTIME_RAW is fast, and precise but not steady */ +#define RTS_CLOCK_HIGHRES CLOCK_UPTIME_RAW + +#elif defined(linux_HOST_OS) || defined(linux_android_HOST_OS) +/* On Linux CLOCK_MONOTONIC and CLOCK_BOOTTIME are precise. We use + * CLOCK_BOOTTIME for consistency with RTS_CLOCK_MONOTONIC above. + */ +#define RTS_CLOCK_HIGHRES CLOCK_BOOTTIME + +#else +#define RTS_CLOCK_HIGHRES CLOCK_MONOTONIC +#endif + + #define RTS_CLOCK_REALTIME CLOCK_REALTIME #define RTS_CLOCK_CPUTIME_THREAD CLOCK_THREAD_CPUTIME_ID #define RTS_CLOCK_CPUTIME_PROCESS CLOCK_PROCESS_CPUTIME_ID ===================================== rts/posix/GetTime.c ===================================== @@ -28,12 +28,18 @@ #warning _POSIX_MONOTONIC_CLOCK not defined, which is likely to be a problem. #endif -void initializeTimer(void) -{ -} - static Time getClockTime(clockid_t clock) { +#if defined(HAVE_CLOCK_GETTIME_NSEC_NP) + /* Non-standard extension on macOS, allowing fewer conversions. */ + uint64_t nsec = clock_gettime_nsec_np(clock); + if (RTS_LIKELY(nsec)) { + return (Time)nsec; + } else { + sysErrorBelch("clock_gettime_nsec_np"); + stg_exit(EXIT_FAILURE); + } +#else struct timespec ts; int res = clock_gettime(clock, &ts); if (RTS_LIKELY(res == 0)) { @@ -42,6 +48,7 @@ static Time getClockTime(clockid_t clock) sysErrorBelch("clock_gettime"); stg_exit(EXIT_FAILURE); } +#endif } Time getCurrentThreadCPUTime(void) @@ -67,6 +74,11 @@ Time getMonotonicTime(void) return getClockTime(RTS_CLOCK_MONOTONIC); } +Time getHighResolutionTime(void) +{ + return getClockTime(RTS_CLOCK_HIGHRES); +} + Time getWallClockTime(void) { return getClockTime(RTS_CLOCK_REALTIME); ===================================== rts/sm/GC.c ===================================== @@ -1525,7 +1525,7 @@ waitForGcThreads (Capability *cap, bool idle_cap[]) uint32_t i, cur_n_gc_entered; Time t0, t1, t2; - t0 = t1 = t2 = getMonotonicTime(); + t0 = t1 = t2 = getHighResolutionTime(); for(i = 0; i < getNumCapabilities(); ++i) { if (i == me || idle_cap[i]) { @@ -1549,7 +1549,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 = getMonotonicTime(); + t2 = getHighResolutionTime(); 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 ===================================== @@ -13,10 +13,6 @@ #include <time.h> #include <sys/time.h> -void initializeTimer(void) -{ -} - static Time getClockTime(clockid_t clock) { struct timespec ts; @@ -44,6 +40,11 @@ Time getMonotonicTime(void) return getClockTime(CLOCK_MONOTONIC); } +Time getHighResolutionTime(void) +{ + return getClockTime(CLOCK_MONOTONIC); +} + Time getWallClockTime(void) { struct timeval tv; ===================================== rts/win32/GetTime.c ===================================== @@ -10,6 +10,7 @@ #include "GetTime.h" #include <windows.h> +#include <realtimeapiset.h> #include <time.h> @@ -48,55 +49,93 @@ Time 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) +/* Note [Windows time/clock functions] + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +A couple useful references for time/clocks: +https://learn.microsoft.com/en-us/windows/win32/sysinfo/acquiring-high-resol... +https://devblogs.microsoft.com/oldnewthing/20170921-00/?p=97057/ + +The advice in the first article is plainly to use QueryPerformanceCounter. It +says this is now always supported in Windows XP and later, and reliable from +Vista, and fast from Windows 7 and 8 (relying on reliably TSCs). The internet +is full of reports that QPC is unreliable, but these do all seem to be from +older Windows versions (or folk lore based on earlier Windows versions or older +hardware). + +Now on the other hand it is worth noting that the article is about the use +cases of high resolution timestamps or measuring time intervals. It's not +really clear that it means its ideal for a monotonic clock, which should be +accurate (not just precise) over longer periods of time. + +In the second article, Raymond notes: + +> And then there are the so-called precise variants of the system timer +> functions. These take the system timer value and combine it with the +> system performance counter to get a high-accuracy timestamp. [...] +> +> + GetSystemTimePreciseAsFileTime +> + QueryInterruptTimePrecise, QueryUnbiasedInterruptTimePrecise +> +> These high-accuracy functions give you the best of both worlds: Time +> correlated with real-world clocks, but with the accuracy of the system +> performance counter. But as noted, it comes at a performance cost. + +The idea here is that the system timer is very accurate (over long time +periods), but is (very) coarse grained, while the TSC is very high frequency +but (at least historically) has been subject to drift over longer periods, +so by combining the two one can get the best of both worlds. + +This makes the "Precise" functions seem like a good choice for a monotonic +clock. Also, they have the benefit of having correspond not-precise ones that +are comparable time sources but coarse and faster. It may well be useful to +have fast coarse clocks, but only if they are coarse measures of the same clock +rather than unrelated clocks. + +Finally, the difference between QueryUnbiasedInterruptTimePrecise and +QueryInterruptTimePrecise is that the "unbiased" clock does not count time when +the system is suspended. We're following the "steady clock" semantics, so we do +want to include suspended time, hence we use QueryInterruptTimePrecise. +*/ +Time getMonotonicTime(void) { - BOOL qpc_supported = QueryPerformanceFrequency(&qpc_frequency); - if (!qpc_supported) - { - qpc_frequency.QuadPart = 0; - } + long long interrupt_time; + /* See Note [Windows time/clock functions] + * The "interrupt time" count is units of 100 nanoseconds. + */ + QueryInterruptTimePrecise(&time); + Time time = interrupt_time * 100ll; /* Convert to nanoseconds */ + return time; } -Time getMonotonicTime(void) +Time getHighResolutionTime(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); + /* Number of ticks per second, provided by QueryPerformanceFrequency */ + static uint64_t 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("getMonotonicNSec: high res timestamps not available"); + stg_exit(EXIT_FAILURE); + } + } - // compute elapsed seconds as double - double secs = (double)system_time.QuadPart / - (double)qpc_frequency.QuadPart; + /* Get the tick count. */ + LARGE_INTEGER tick_count; + QueryPerformanceCounter(&tick_count); - // return elapsed time in nanoseconds - return (Time)(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 (Time)count * 1000000; - } + /* 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; } Time getWallClockTime(void) @@ -104,17 +143,14 @@ 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, + /* See Note [Windows time/clock functions] + 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); + 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 ===================================== 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/1f64668d5dd34d61c3a249aee04a4df... -- View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/1f64668d5dd34d61c3a249aee04a4df... 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