Duncan Coutts pushed to branch wip/dcoutts/posix-time at Glasgow Haskell Compiler / GHC

Commits:

12 changed files:

Changes:

  • changelog.d/clock_gettime
    1
    +section: rts
    
    2
    +synopsis: The RTS now uses the `clock_gettime` monotonic clock on all POSIX platforms.
    
    3
    +issues: #28119 #14233
    
    4
    +mrs: !16968
    
    5
    +description:
    
    6
    +  Having a good monotonic clock source is vital for concurrent programming.
    
    7
    +  Historically platform APIs for high precision monotonic time have not been
    
    8
    +  widely available in a consistent standard form, and GHC was forced to depend
    
    9
    +  on a hodge podge of different APIs (some of which did not even provide
    
    10
    +  monotonic time). POSIX.1-2008 mandated the `clock_gettime` API, and this is
    
    11
    +  now old enough and widely supported enough that the RTS can now use this
    
    12
    +  with the `CLOCK_MONOTONIC` and `CLOCK_REALTIME` clocks for all of its internal
    
    13
    +  timing needs on all POSIX platforms.
    
    14
    +
    
    15
    +  The compatibility implication is that some older POSIX platforms that do not
    
    16
    +  support the POSIX.1-2008 standard will no longer be supported. To the best of
    
    17
    +  our knowledge the main platforms impacted are versions of macOS prior to
    
    18
    +  version 10.12 (released 2016, EOL 2019).

  • rts/GetTime.h
    ... ... @@ -11,18 +11,76 @@
    11 11
     
    
    12 12
     #include "BeginPrivate.h"
    
    13 13
     
    
    14
    -void initializeTimer       (void);
    
    14
    +/* Note [Meaning of clocks]
    
    15
    + * ~~~~~~~~~~~~~~~~~~~~~~~~
    
    16
    + *
    
    17
    + * Clock terminology
    
    18
    + *
    
    19
    + *  1. monotonic time: non-decreasing. This is for measuring intervals, not
    
    20
    + *     subject to time jumps (e.g. due to NTP or user fixing the time).
    
    21
    + *  2. real / wall clock time: corresponding to real world UTC time.
    
    22
    + *  3. CPU time: time spent by threads/processes running on a CPU.
    
    23
    + *  4. steady clock: (following the C++11 library definition): the time
    
    24
    + *     between ticks of this clock is constant. In particular this implies it
    
    25
    + *     _does_ keep time even when the system is suspended/hibernated. Note that
    
    26
    + *     a wall clock must be steady, whereas a monotonic clock need not be.
    
    27
    + *
    
    28
    + * An ideal clock would be:
    
    29
    + *  1. accurate: able to keep time over long periods;
    
    30
    + *  2. precise: a high resolution of clock measurement;
    
    31
    + *  3. fast: the time duration to measure the clock.
    
    32
    + *
    
    33
    + * Real clocks available on platforms must make compromises.
    
    34
    + *
    
    35
    + * We provide a choice of clocks that pick the best platform clocks given
    
    36
    + * different priorities between these desires.
    
    37
    + *
    
    38
    + * 1. A monotonic, steady, accurate clock: getMonotonicTime
    
    39
    + * 2. A precise monotonic clock: getHighResolutionTime
    
    40
    + * 3. An accurate real time clock: getWallClockTime
    
    41
    + *
    
    42
    + * We could also (but do not currently) provide:
    
    43
    + * 4. A fast monotonic clock (but not comparable to the accurate clock)
    
    44
    + * 5. A fast real time clock (a less precise real time clock, and comparable)
    
    45
    + *
    
    46
    + * In general these clocks are _not_ comparable. The only ones that _could_ be
    
    47
    + * comparable (if we were to need and provide them) are low res clocks that are
    
    48
    + * (guaranteed) to be low resolution measures of the same clock.
    
    49
    + */
    
    15 50
     
    
    16
    -/* Get the current time in a monotonic clock.
    
    51
    +/* Get the current time in a monotonic, steady, accurate clock.
    
    52
    + * See Note [Meaning of clocks].
    
    17 53
      *
    
    18 54
      * The time is represented as nanoseconds since an arbitrary epoch.
    
    55
    + *
    
    56
    + * This is the clock used for user timeouts like threadDelay.
    
    19 57
      */
    
    20 58
     Time getMonotonicTime(void);
    
    21 59
     
    
    22
    -/* Get the current wall clock time.
    
    60
    +/* Get the time in a monotonic, high resolution clock.
    
    61
    + * See Note [Meaning of clocks].
    
    62
    + *
    
    63
    + * This is intended to be the most high resolution / precise clock available on
    
    64
    + * the platform. It is suitable for timing operations with maximum available
    
    65
    + * precision.
    
    66
    + *
    
    67
    + * It is not necessarily accurate at keeping time over long time periods (i.e.
    
    68
    + * may be subject to time drift). It is not necessarily steady: it may or may
    
    69
    + * not include time while the system is suspend.
    
    70
    + *
    
    71
    + * This is the clock used for measuring timing of activities within the RTS:
    
    72
    + * RTS stats, profiling and eventlog timestamps.
    
    73
    + */
    
    74
    +Time getHighResolutionTime(void);
    
    75
    +
    
    76
    +/* Get the time in a real time, accurate clock.
    
    77
    + * See Note [Meaning of clocks].
    
    23 78
      *
    
    24 79
      * The time is represented as nanoseconds since the Unix epoch
    
    25 80
      * (1970-01-01 00:00).
    
    81
    + *
    
    82
    + * This clock is not used much, but is emitted into eventlogs on start to
    
    83
    + * enable matching the eventlog timestamps with wall clock time.
    
    26 84
      */
    
    27 85
     Time getWallClockTime(void);
    
    28 86
     
    

  • rts/RtsStartup.c
    ... ... @@ -360,9 +360,6 @@ hs_init_ghc(int *argc, char **argv[], RtsConfig rts_config)
    360 360
         /* Initialise the stats department, phase 0 */
    
    361 361
         initStats0();
    
    362 362
     
    
    363
    -    /* Initialize system timer before starting to collect stats */
    
    364
    -    initializeTimer();
    
    365
    -
    
    366 363
         /* Next we do is grab the start time...just in case we're
    
    367 364
          * collecting timing statistics.
    
    368 365
          */
    

  • rts/RtsUtils.c
    ... ... @@ -31,10 +31,6 @@ extern char *ctime_r(const time_t *, char *);
    31 31
     #include <fcntl.h>
    
    32 32
     #endif
    
    33 33
     
    
    34
    -#if defined(HAVE_GETTIMEOFDAY)
    
    35
    -#include <sys/time.h>
    
    36
    -#endif
    
    37
    -
    
    38 34
     #include <stdlib.h>
    
    39 35
     #include <string.h>
    
    40 36
     #include <stdarg.h>
    
    ... ... @@ -207,31 +203,6 @@ exitHeapOverflow(void)
    207 203
         stg_exit(EXIT_HEAPOVERFLOW);
    
    208 204
     }
    
    209 205
     
    
    210
    -/* -----------------------------------------------------------------------------
    
    211
    -   Sleep for the given period of time.
    
    212
    -   -------------------------------------------------------------------------- */
    
    213
    -
    
    214
    -/* Returns -1 on failure but handles EINTR internally. On Windows this will
    
    215
    - * only have millisecond precision. */
    
    216
    -int rtsSleep(Time t)
    
    217
    -{
    
    218
    -#if defined(_WIN32)
    
    219
    -    // N.B. we can't use nanosleep on Windows as it would incur a pthreads
    
    220
    -    // dependency. See #18272.
    
    221
    -    Sleep(TimeToMS(t));
    
    222
    -    return 0;
    
    223
    -#else
    
    224
    -    struct timespec req;
    
    225
    -    req.tv_sec = TimeToSeconds(t);
    
    226
    -    req.tv_nsec = TimeToNS(t - req.tv_sec * TIME_RESOLUTION);
    
    227
    -    int ret;
    
    228
    -    do {
    
    229
    -        ret = nanosleep(&req, &req);
    
    230
    -    } while (ret == -1 && errno == EINTR);
    
    231
    -    return ret;
    
    232
    -#endif /* _WIN32 */
    
    233
    -}
    
    234
    -
    
    235 206
     /* -----------------------------------------------------------------------------
    
    236 207
        Get the current time as a string.  Used in profiling reports.
    
    237 208
        -------------------------------------------------------------------------- */
    

  • rts/Stats.c
    ... ... @@ -75,18 +75,22 @@ static void statsFlush( void );
    75 75
     static void statsClose( void );
    
    76 76
     
    
    77 77
     /* -----------------------------------------------------------------------------
    
    78
    -   Current elapsed time
    
    78
    +   Current time
    
    79
    +
    
    80
    +   We use the high resolution clock, not the accurate steady clock.
    
    81
    +   This is for measuring how long things take over relatively short intervals.
    
    79 82
        ------------------------------------------------------------------------- */
    
    80 83
     
    
    84
    +/* Used for eventlog timestamps, and matching census->rtime */
    
    81 85
     Time stat_getElapsedTime(void)
    
    82 86
     {
    
    83
    -    return getMonotonicTime() - start_init_elapsed;
    
    87
    +    return getHighResolutionTime() - start_init_elapsed;
    
    84 88
     }
    
    85 89
     
    
    86 90
     static void getProcessTimes(Time *user, Time *elapsed)
    
    87 91
     {
    
    88 92
         *user    = getProcessCPUTime();
    
    89
    -    *elapsed = getMonotonicTime();
    
    93
    +    *elapsed = getHighResolutionTime();
    
    90 94
     }
    
    91 95
     
    
    92 96
     /* ---------------------------------------------------------------------------
    
    ... ... @@ -301,7 +305,7 @@ stat_endExit(void)
    301 305
     void
    
    302 306
     stat_startGCSync (gc_thread *gct)
    
    303 307
     {
    
    304
    -    gct->gc_sync_start_elapsed = getMonotonicTime();
    
    308
    +    gct->gc_sync_start_elapsed = getHighResolutionTime();
    
    305 309
     }
    
    306 310
     
    
    307 311
     void
    
    ... ... @@ -309,7 +313,7 @@ stat_startNonmovingGc (void)
    309 313
     {
    
    310 314
         ACQUIRE_LOCK(&stats_mutex);
    
    311 315
         start_nonmoving_gc_cpu = getCurrentThreadCPUTime();
    
    312
    -    start_nonmoving_gc_elapsed = getMonotonicTime();
    
    316
    +    start_nonmoving_gc_elapsed = getHighResolutionTime();
    
    313 317
         RELEASE_LOCK(&stats_mutex);
    
    314 318
     }
    
    315 319
     
    
    ... ... @@ -317,7 +321,7 @@ void
    317 321
     stat_endNonmovingGc (void)
    
    318 322
     {
    
    319 323
         Time cpu = getCurrentThreadCPUTime();
    
    320
    -    Time elapsed = getMonotonicTime();
    
    324
    +    Time elapsed = getHighResolutionTime();
    
    321 325
     
    
    322 326
         ACQUIRE_LOCK(&stats_mutex);
    
    323 327
         stats.gc.nonmoving_gc_elapsed_ns = elapsed - start_nonmoving_gc_elapsed;
    
    ... ... @@ -336,7 +340,7 @@ void
    336 340
     stat_startNonmovingGcSync (void)
    
    337 341
     {
    
    338 342
         ACQUIRE_LOCK(&stats_mutex);
    
    339
    -    start_nonmoving_gc_sync_elapsed = getMonotonicTime();
    
    343
    +    start_nonmoving_gc_sync_elapsed = getHighResolutionTime();
    
    340 344
         RELEASE_LOCK(&stats_mutex);
    
    341 345
         traceConcSyncBegin();
    
    342 346
     }
    
    ... ... @@ -344,7 +348,7 @@ stat_startNonmovingGcSync (void)
    344 348
     void
    
    345 349
     stat_endNonmovingGcSync (void)
    
    346 350
     {
    
    347
    -    Time end_elapsed = getMonotonicTime();
    
    351
    +    Time end_elapsed = getHighResolutionTime();
    
    348 352
         ACQUIRE_LOCK(&stats_mutex);
    
    349 353
         stats.gc.nonmoving_gc_sync_elapsed_ns = end_elapsed - start_nonmoving_gc_sync_elapsed;
    
    350 354
         stats.nonmoving_gc_sync_elapsed_ns +=  stats.gc.nonmoving_gc_sync_elapsed_ns;
    
    ... ... @@ -451,7 +455,7 @@ stat_startGC (Capability *cap, gc_thread *gct)
    451 455
             gct->gc_start_cpu = getCurrentThreadCPUTime();
    
    452 456
         }
    
    453 457
     
    
    454
    -    gct->gc_start_elapsed = getMonotonicTime();
    
    458
    +    gct->gc_start_elapsed = getHighResolutionTime();
    
    455 459
     #if !defined(THREADED_RTS)
    
    456 460
         // Non-threaded RTS has no sync phase. Initializing in this way makes the
    
    457 461
         // calculated statistics correctly read zero.
    

  • rts/configure.ac
    ... ... @@ -206,6 +206,7 @@ dnl ** We now require clock_gettime for our monotonic clock.
    206 206
     if test "$ghc_host_os" != "mingw32" ; then
    
    207 207
       AC_CHECK_FUNCS([clock_gettime], [],
    
    208 208
         AC_MSG_ERROR([The POSIX.1-2008 function 'clock_gettime' is required but is not available]))
    
    209
    +  AC_CHECK_FUNCS([clock_gettime_nsec_np])
    
    209 210
     fi
    
    210 211
     
    
    211 212
     dnl ** check for Apple's "interesting" long double compatibility scheme
    

  • rts/posix/Clock.h
    ... ... @@ -8,7 +8,43 @@
    8 8
     
    
    9 9
     #pragma once
    
    10 10
     
    
    11
    +
    
    12
    +#if defined(linux_HOST_OS) || defined(linux_android_HOST_OS)
    
    13
    +/* On Linux the CLOCK_MONOTONIC does not count time while the machine is
    
    14
    + * suspend. We have defined getMonotonicTime to be a steady clock (which does
    
    15
    + * count time while suspend). So on Linux we use CLOCK_BOOTTIME:
    
    16
    + *
    
    17
    + * > A  nonsettable  system-wide  clock  that is identical to CLOCK_MONOTONIC,
    
    18
    + * > except that it also includes any time that the system is suspended.
    
    19
    + *
    
    20
    + * The only downside is that there is no CLOCK_BOOTTIME_COARSE, only
    
    21
    + * CLOCK_MONOTONIC_COARSE.
    
    22
    + */
    
    23
    +#define RTS_CLOCK_MONOTONIC CLOCK_BOOTTIME
    
    24
    +
    
    25
    +#else
    
    26
    +/* On (most?) other POSIX platforms the CLOCK_MONOTONIC counts time while the
    
    27
    + * machine is suspend. In particular this is true on FreeBSD and macOS.
    
    28
    + */
    
    11 29
     #define RTS_CLOCK_MONOTONIC CLOCK_MONOTONIC
    
    30
    +#endif
    
    31
    +
    
    32
    +
    
    33
    +#if defined(darwin_HOST_OS) || defined(ios_HOST_OS)
    
    34
    +/* On macOS CLOCK_UPTIME_RAW is fast, and precise but not steady */
    
    35
    +#define RTS_CLOCK_HIGHRES   CLOCK_UPTIME_RAW
    
    36
    +
    
    37
    +#elif defined(linux_HOST_OS) || defined(linux_android_HOST_OS)
    
    38
    +/* On Linux CLOCK_MONOTONIC and CLOCK_BOOTTIME are precise. We use
    
    39
    + * CLOCK_BOOTTIME for consistency with RTS_CLOCK_MONOTONIC above.
    
    40
    + */
    
    41
    +#define RTS_CLOCK_HIGHRES   CLOCK_BOOTTIME
    
    42
    +
    
    43
    +#else
    
    44
    +#define RTS_CLOCK_HIGHRES   CLOCK_MONOTONIC
    
    45
    +#endif
    
    46
    +
    
    47
    +
    
    12 48
     #define RTS_CLOCK_REALTIME  CLOCK_REALTIME
    
    13 49
     #define RTS_CLOCK_CPUTIME_THREAD CLOCK_THREAD_CPUTIME_ID
    
    14 50
     #define RTS_CLOCK_CPUTIME_PROCESS CLOCK_PROCESS_CPUTIME_ID

  • rts/posix/GetTime.c
    ... ... @@ -28,12 +28,18 @@
    28 28
     #warning _POSIX_MONOTONIC_CLOCK not defined, which is likely to be a problem.
    
    29 29
     #endif
    
    30 30
     
    
    31
    -void initializeTimer(void)
    
    32
    -{
    
    33
    -}
    
    34
    -
    
    35 31
     static Time getClockTime(clockid_t clock)
    
    36 32
     {
    
    33
    +#if defined(HAVE_CLOCK_GETTIME_NSEC_NP)
    
    34
    +    /* Non-standard extension on macOS, allowing fewer conversions. */
    
    35
    +    uint64_t nsec = clock_gettime_nsec_np(clock);
    
    36
    +    if (RTS_LIKELY(nsec)) {
    
    37
    +        return (Time)nsec;
    
    38
    +    } else {
    
    39
    +        sysErrorBelch("clock_gettime_nsec_np");
    
    40
    +        stg_exit(EXIT_FAILURE);
    
    41
    +    }
    
    42
    +#else
    
    37 43
         struct timespec ts;
    
    38 44
         int res = clock_gettime(clock, &ts);
    
    39 45
         if (RTS_LIKELY(res == 0)) {
    
    ... ... @@ -42,6 +48,7 @@ static Time getClockTime(clockid_t clock)
    42 48
             sysErrorBelch("clock_gettime");
    
    43 49
             stg_exit(EXIT_FAILURE);
    
    44 50
         }
    
    51
    +#endif
    
    45 52
     }
    
    46 53
     
    
    47 54
     Time getCurrentThreadCPUTime(void)
    
    ... ... @@ -67,6 +74,11 @@ Time getMonotonicTime(void)
    67 74
         return getClockTime(RTS_CLOCK_MONOTONIC);
    
    68 75
     }
    
    69 76
     
    
    77
    +Time getHighResolutionTime(void)
    
    78
    +{
    
    79
    +    return getClockTime(RTS_CLOCK_HIGHRES);
    
    80
    +}
    
    81
    +
    
    70 82
     Time getWallClockTime(void)
    
    71 83
     {
    
    72 84
         return getClockTime(RTS_CLOCK_REALTIME);
    

  • rts/sm/GC.c
    ... ... @@ -1525,7 +1525,7 @@ waitForGcThreads (Capability *cap, bool idle_cap[])
    1525 1525
         uint32_t i, cur_n_gc_entered;
    
    1526 1526
         Time t0, t1, t2;
    
    1527 1527
     
    
    1528
    -    t0 = t1 = t2 = getMonotonicTime();
    
    1528
    +    t0 = t1 = t2 = getHighResolutionTime();
    
    1529 1529
     
    
    1530 1530
         for(i = 0; i < getNumCapabilities(); ++i) {
    
    1531 1531
             if (i == me || idle_cap[i]) {
    
    ... ... @@ -1549,7 +1549,7 @@ waitForGcThreads (Capability *cap, bool idle_cap[])
    1549 1549
             // this 1ms timeout is not well justified. It's the shortest timeout we
    
    1550 1550
             // can use on windows. It seems to work well for me.
    
    1551 1551
             timedWaitCondition(&gc_entry_arrived_cv, &gc_entry_mutex, USToTime(1000));
    
    1552
    -        t2 = getMonotonicTime();
    
    1552
    +        t2 = getHighResolutionTime();
    
    1553 1553
             if (RtsFlags.GcFlags.longGCSync != 0 &&
    
    1554 1554
                 t2 - t1 > RtsFlags.GcFlags.longGCSync) {
    
    1555 1555
                 // best not to hold the mutex while we call a hook function
    

  • rts/wasm/GetTime.c
    ... ... @@ -13,10 +13,6 @@
    13 13
     #include <time.h>
    
    14 14
     #include <sys/time.h>
    
    15 15
     
    
    16
    -void initializeTimer(void)
    
    17
    -{
    
    18
    -}
    
    19
    -
    
    20 16
     static Time getClockTime(clockid_t clock)
    
    21 17
     {
    
    22 18
         struct timespec ts;
    
    ... ... @@ -44,6 +40,11 @@ Time getMonotonicTime(void)
    44 40
         return getClockTime(CLOCK_MONOTONIC);
    
    45 41
     }
    
    46 42
     
    
    43
    +Time getHighResolutionTime(void)
    
    44
    +{
    
    45
    +    return getClockTime(CLOCK_MONOTONIC);
    
    46
    +}
    
    47
    +
    
    47 48
     Time getWallClockTime(void)
    
    48 49
     {
    
    49 50
         struct timeval tv;
    

  • rts/win32/GetTime.c
    ... ... @@ -10,6 +10,7 @@
    10 10
     #include "GetTime.h"
    
    11 11
     
    
    12 12
     #include <windows.h>
    
    13
    +#include <realtimeapiset.h>
    
    13 14
     
    
    14 15
     #include <time.h>
    
    15 16
     
    
    ... ... @@ -48,55 +49,93 @@ Time getProcessCPUTime(void)
    48 49
         return fileTimeToRtsTime(userTime);
    
    49 50
     }
    
    50 51
     
    
    51
    -// Number of ticks per second used by the QueryPerformanceFrequency
    
    52
    -// implementation, represented by a 64-bit union type.
    
    53
    -static LARGE_INTEGER qpc_frequency = {.QuadPart = 0};
    
    54
    -
    
    55
    -// Initialize qpc_frequency. This function should be called before any call to
    
    56
    -// getMonotonicNSec.  If QPC is not supported on this system, qpc_frequency is
    
    57
    -// set to 0.
    
    58
    -void initializeTimer(void)
    
    52
    +/* Note [Windows time/clock functions]
    
    53
    +   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    54
    +
    
    55
    +A couple useful references for time/clocks:
    
    56
    +https://learn.microsoft.com/en-us/windows/win32/sysinfo/acquiring-high-resolution-time-stamps
    
    57
    +https://devblogs.microsoft.com/oldnewthing/20170921-00/?p=97057/
    
    58
    +
    
    59
    +The advice in the first article is plainly to use QueryPerformanceCounter. It
    
    60
    +says this is now always supported in Windows XP and later, and reliable from
    
    61
    +Vista, and fast from Windows 7 and 8 (relying on reliably TSCs). The internet
    
    62
    +is full of reports that QPC is unreliable, but these do all seem to be from
    
    63
    +older Windows versions (or folk lore based on earlier Windows versions or older
    
    64
    +hardware).
    
    65
    +
    
    66
    +Now on the other hand it is worth noting that the article is about the use
    
    67
    +cases of high resolution timestamps or measuring time intervals. It's not
    
    68
    +really clear that it means its ideal for a monotonic clock, which should be
    
    69
    +accurate (not just precise) over longer periods of time.
    
    70
    +
    
    71
    +In the second article, Raymond notes:
    
    72
    +
    
    73
    +> And then there are the so-called precise variants of the system timer
    
    74
    +> functions. These take the system timer value and combine it with the
    
    75
    +> system performance counter to get a high-accuracy timestamp. [...]
    
    76
    +>
    
    77
    +>  + GetSystemTimePreciseAsFileTime
    
    78
    +>  + QueryInterruptTimePrecise, QueryUnbiasedInterruptTimePrecise
    
    79
    +>
    
    80
    +> These high-accuracy functions give you the best of both worlds: Time
    
    81
    +> correlated with real-world clocks, but with the accuracy of the system
    
    82
    +> performance counter. But as noted, it comes at a performance cost.
    
    83
    +
    
    84
    +The idea here is that the system timer is very accurate (over long time
    
    85
    +periods), but is (very) coarse grained, while the TSC is very high frequency
    
    86
    +but (at least historically) has been subject to drift over longer periods,
    
    87
    +so by combining the two one can get the best of both worlds.
    
    88
    +
    
    89
    +This makes the "Precise" functions seem like a good choice for a monotonic
    
    90
    +clock. Also, they have the benefit of having correspond not-precise ones that
    
    91
    +are comparable time sources but coarse and faster. It may well be useful to
    
    92
    +have fast coarse clocks, but only if they are coarse measures of the same clock
    
    93
    +rather than unrelated clocks.
    
    94
    +
    
    95
    +Finally, the difference between Query­Unbiased­Interrupt­Time­Precise and
    
    96
    +Query­Interrupt­Time­Precise is that the "unbiased" clock does not count time when
    
    97
    +the system is suspended. We're following the "steady clock" semantics, so we do
    
    98
    +want to include suspended time, hence we use Query­Interrupt­Time­Precise.
    
    99
    +*/
    
    100
    +Time getMonotonicTime(void)
    
    59 101
     {
    
    60
    -    BOOL qpc_supported = QueryPerformanceFrequency(&qpc_frequency);
    
    61
    -    if (!qpc_supported)
    
    62
    -    {
    
    63
    -        qpc_frequency.QuadPart = 0;
    
    64
    -    }
    
    102
    +    long long interrupt_time;
    
    103
    +    /* See Note [Windows time/clock functions]
    
    104
    +     * The "interrupt time" count is units of 100 nanoseconds.
    
    105
    +     */
    
    106
    +    QueryInterruptTimePrecise(&time);
    
    107
    +    Time time = interrupt_time * 100ll; /* Convert to nanoseconds */
    
    108
    +    return time;
    
    65 109
     }
    
    66 110
     
    
    67
    -Time getMonotonicTime(void)
    
    111
    +Time getHighResolutionTime(void)
    
    68 112
     {
    
    69
    -    if (qpc_frequency.QuadPart)
    
    70
    -    {
    
    71
    -        // system_time is a 64-bit union type used to represent the
    
    72
    -        // tick count returned by QueryPerformanceCounter
    
    73
    -        LARGE_INTEGER system_time;
    
    74
    -
    
    75
    -        // get the tick count.
    
    76
    -        QueryPerformanceCounter(&system_time);
    
    113
    +    /* Number of ticks per second, provided by QueryPerformanceFrequency */
    
    114
    +    static uint64_t ticks_per_sec = 0;
    
    115
    +
    
    116
    +    /* Initialize ticks_per_sec on the first call. It should not matter if two
    
    117
    +       threads race to do this. The result should be the same. */
    
    118
    +    if (RTS_UNLIKELY(RELAXED_LOAD_ALWAYS(&ticks_per_sec) == 0)) {
    
    119
    +        LARGE_INTEGER qpc_frequency; // a 64-bit union type
    
    120
    +        if (QueryPerformanceFrequency(&qpc_frequency)) {
    
    121
    +            RELAXED_STORE_ALWAYS(&ticks_per_sec, qpc_frequency.QuadPart);
    
    122
    +        } else {
    
    123
    +            /* This should be impossible now. */
    
    124
    +            sysErrorBelch("getMonotonicNSec: high res timestamps not available");
    
    125
    +            stg_exit(EXIT_FAILURE);
    
    126
    +        }
    
    127
    +    }
    
    77 128
     
    
    78
    -        // compute elapsed seconds as double
    
    79
    -        double secs = (double)system_time.QuadPart /
    
    80
    -                      (double)qpc_frequency.QuadPart;
    
    129
    +    /* Get the tick count. */
    
    130
    +    LARGE_INTEGER tick_count;
    
    131
    +    QueryPerformanceCounter(&tick_count);
    
    81 132
     
    
    82
    -        // return elapsed time in nanoseconds
    
    83
    -        return (Time)(secs * 1e9);
    
    84
    -    }
    
    85
    -    else // fallback to GetTickCount
    
    86
    -    {
    
    87
    -        // TODO: Remove this code path, it cannot be taken because
    
    88
    -        // `QueryPerformanceFrequency` cannot fail on Windows >= XP
    
    89
    -        // and GHC no longer supports Windows <= XP.
    
    90
    -        // See https://gitlab.haskell.org/ghc/ghc/issues/14233
    
    91
    -
    
    92
    -        // NOTE: GetTickCount is a 32-bit millisecond value, so it wraps around
    
    93
    -        // every 49 days.
    
    94
    -        DWORD count = GetTickCount();
    
    95
    -
    
    96
    -        // getTickCount is in milliseconds, so multiply it by 1000000 to get
    
    97
    -        // nanoseconds.
    
    98
    -        return (Time)count * 1000000;
    
    99
    -    }
    
    133
    +    /* Compute elapsed time in nanoseconds. If avoiding float, we must multiply
    
    134
    +     * by nanoseconds first (1e9) and then divide by ticks per sec. The
    
    135
    +     * intermediate result can overflow a 64bit integer. So we use 128bit.
    
    136
    +     */
    
    137
    +    return ((__uint128_t)tick_count.QuadPart * (__uint128_t)1000000000ull)
    
    138
    +         / (__uint128_t)ticks_per_sec;
    
    100 139
     }
    
    101 140
     
    
    102 141
     Time getWallClockTime(void)
    
    ... ... @@ -104,17 +143,14 @@ Time getWallClockTime(void)
    104 143
         /* Windows has a bunch of time APIs but none that directly give
    
    105 144
            us unix epoch time, so we have to do a little dance. */
    
    106 145
     
    
    107
    -    SYSTEMTIME systime;
    
    108 146
         FILETIME filetime;
    
    109 147
         ULARGE_INTEGER unixtime;
    
    110 148
     
    
    111
    -    /* Windows SYSTEMTIME is a big struct with fields for
    
    112
    -       year, month, day, hour, minute, second, millisecond. */
    
    113
    -    GetSystemTime(&systime);
    
    114
    -    /* Windows FILETIME timestamps use an epoch-based time,
    
    149
    +    /* See Note [Windows time/clock functions]
    
    150
    +       Windows FILETIME timestamps use an epoch-based time,
    
    115 151
            using a 64bit unsigned word. The time is measured in
    
    116 152
            units of 100 nanoseconds since an epoch of 1601. */
    
    117
    -    SystemTimeToFileTime(&systime, &filetime);
    
    153
    +    GetSystemTimePreciseAsFileTime(&filetime);
    
    118 154
     
    
    119 155
         /* FILETIME isn't directly a 64bit word, but a struct with
    
    120 156
            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)
    227 227
     
    
    228 228
         StgTimeoutQueue *root = EMPTY;
    
    229 229
         Time before, after;
    
    230
    -    initializeTimer();
    
    231 230
     
    
    232 231
         /* Init */
    
    233 232
         StgTimeoutQueue *elems = calloc(N, sizeof(StgTimeoutQueue));