perf(libc): add steady_clock fast path in PreciseSleepUntil #6620

Merged
hamb3r merged 5 commits from upstream-pr/6620 into main 2026-10-18 20:32:23 +00:00
hamb3r commented 2026-10-15 23:14:54 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by hamb3r on 2026-10-15T23:14:54Z.


What

  • Extract PreciseQpcFrequency() so PreciseSleepFromCounterWithTimer and PreciseSleepUntil share the cached QueryPerformanceFrequency value on Windows.
  • Add a std::chrono::steady_clock fast path in PreciseSleepUntil on both Windows (PreciseQpcFrequency() == 10000000ULL, 10 MHz QPC) and POSIX/Linux (PreciseMonotonicNanos()) that converts deadline.time_since_epoch() to hardware clock ticks before sampling the hardware clock and delegates directly to PreciseSleepFromCounter / PreciseSleepFromNanos:
    1. Eliminates 2 redundant steady_clock::now() reads per call: On current main, PreciseSleepUntil reads the hardware clock (QueryPerformanceCounter on Windows, PreciseMonotonicNanos on POSIX), then immediately calls TClock::now() (which on Windows MinGW-w64 libstdc++ calls libwinpthread!clock_gettime(CLOCK_MONOTONIC) -> uncached QueryPerformanceFrequency + QueryPerformanceCounter + three 64-bit idiv instructions, and on Linux calls steady_clock::now()@PLT), and then calls TClock::now() a third time in the post-wait epilogue loop — performing 3 hardware clock reads even when the deadline has already expired.
    2. Eliminates T_0 vs T_1 sampling skew: On main, the initial hardware counter is sampled at T_0 and now = TClock::now() is sampled at T_1 > T_0. Computing remaining = deadline - now (deadline - T_1) and adding it to the counter sampled at T_0 causes PreciseSleepFromCounter / PreciseSleepFromNanos to wake up at T_0 + (deadline - T_1) = deadline - (T_1 - T_0), systematically undershooting deadline and forcing execution into the for (auto current = TClock::now(); ...) epilogue loop.
    3. Eliminates * 100 and 128-bit / 100 division after QueryPerformanceCounter on Windows (10 MHz): By the integer identity
      \left\lceil \frac{\text{deadlineNs} - 100 \cdot \text{counter}}{100} \right\rceil = \left\lceil \frac{\text{deadlineNs}}{100} \right\rceil - \text{counter}
      checking if (rawDeadline <= 0) [[unlikely]] { return; } and precomputing targetHns before QueryPerformanceCounter(&counter) removes imul (* 100), 128-bit mul 0x28f5c28f5c28f5c3 (/ 100), and add from the timing-critical window after sampling the counter, leaving a single sub instruction (targetHns - nowTicks). For coarser time_point durations (such as microseconds), division is eliminated completely (add + lea for * 10).
  • Align PreciseMonotonicNanos() on Apple libc++ (__APPLE__ && _LIBCPP_VERSION && CLOCK_MONOTONIC_RAW) to use clock_gettime(CLOCK_MONOTONIC_RAW, &ts) so it shares the exact clock source and sub-microsecond resolution of libc++'s std::chrono::steady_clock::now() (which also fixes PreciseSleepUs returning up to 1 us early against steady_clock on macOS due to CLOCK_MONOTONIC's 1000 ns resolution), and gate the non-Windows steady_clock fast path to configurations with guaranteed matching clock sources.
  • Add unit test coverage in core/libs/tests/PreciseWait.cpp for zero-epoch (steady_clock::time_point{}) and coarse-duration (time_point<steady_clock, microseconds>) deadlines.
llvm-objdump -d --x86-asm-syntax=intel (Windows x64 PreciseSleepUntil<steady_clock>: Before vs After)

Before (main: calls QueryPerformanceCounter, then calls steady_clock::now(), performs 128-bit / 100 division after QPC, and loops on steady_clock::now() again at exit):

  14: call    qword ptr [rip + __imp_QueryPerformanceCounter] ; QPC read #1 (T0)
  1a: call    std::chrono::steady_clock::now                  ; QPC read #2 (T1)
  25: mov     rcx, qword ptr [rsi]
  28: sub     rcx, rax                                        ; deadlineNs - nowNs
  2b: jle     0x5b
  2d: add     rcx, 0x63
  31: movabs  rax, 0x28f5c28f5c28f5c3
  3b: mul     rcx                                             ; 128-bit / 100 AFTER clock read!
  3e: shr     rdx, 0x6
  42: mov     rcx, qword ptr [rsp + 0x38]
  47: call    PreciseSleepFromCounter                         ; wakes up (T1 - T0) before deadline!
  5b: call    std::chrono::steady_clock::now                  ; QPC read #3+ in epilogue loop
  60: cmp     rax, qword ptr [rsi]
  63: jge     0x7c

After (PR: 0 calls to steady_clock::now(); targetHns precomputed before QueryPerformanceCounter; only mov + sub + jbe after QueryPerformanceCounter):

  1c: mov     rax, qword ptr [rcx]
  1f: test    rax, rax
  22: jle     0xdc                                            ; rawDeadline <= 0 -> immediate return (0 QPC reads!)
  28: add     rax, 0x63
  2c: shr     rax, 0x2
  30: movabs  rcx, 0x28f5c28f5c28f5c3
  3a: mul     rcx                                             ; targetHns precomputed BEFORE QPC read!
  3d: mov     rsi, rdx
  40: shr     rsi, 0x2
  44: lea     rcx, [rsp + 0x40]
  49: call    qword ptr [rip + __imp_QueryPerformanceCounter] ; single QPC read!
  4f: mov     rax, qword ptr [rsp + 0x40]
  54: mov     rcx, rsi
  57: sub     rcx, rax                                        ; remainingTicks = targetHns - nowTicks (1 instruction!)
  5a: jbe     0xdc                                            ; already reached -> immediate return

After (for time_point<steady_clock, microseconds>: 0 divisions anywhere in the function):

  28: add     rax, rax
  2b: lea     rsi, [rax + 4*rax]                              ; targetHns = rawDeadlineUs * 10 (2 instructions!)
  2f: lea     rcx, [rsp + 0x40]
  34: call    qword ptr [rip + __imp_QueryPerformanceCounter]
  3a: mov     rax, qword ptr [rsp + 0x40]
  3f: mov     rcx, rsi
  42: sub     rcx, rax                                        ; remainingTicks = targetHns - nowTicks
  45: jbe     0xc7
objdump -d -M intel (Linux x86_64 PreciseSleepUntil<steady_clock>: Before vs After)

Before (main: calls clock_gettime, then immediately calls steady_clock::now()@PLT, and calls steady_clock::now()@PLT again in the epilogue loop):

  1bee: mov    edi, 0x1
  1bf3: call   clock_gettime@plt                              ; clock read #1: PreciseMonotonicNanos() (T0)
  1bf8: mov    rbp, QWORD PTR [rsp+0x10]
  1bfd: mov    r12, QWORD PTR [rsp+0x18]
  1c02: call   std::chrono::_V2::steady_clock::now()@plt      ; clock read #2: steady_clock::now() (T1)
  1c07: mov    rdx, QWORD PTR [rbx]
  1c0a: cmp    rax, rdx
  1c0d: jge    0x1cf0                                         ; -> clock read #3: steady_clock::now()@plt in epilogue

After (PR: 0 calls to steady_clock::now()@PLT; single clock_gettime call):

  1a24: test   rdi, rdi
  1a27: jle    0x1a5c                                         ; rawDeadline <= 0 -> immediate return (0 clock reads!)
  1a35: lea    rsi, [rsp+0x10]
  1a3a: mov    edi, 0x1
  1a3f: call   clock_gettime@plt                              ; single clock read!
  1a44: imul   rax, QWORD PTR [rsp+0x10], 0x3b9aca00
  1a4d: add    rax, QWORD PTR [rsp+0x18]
  1a52: cmp    rax, rbx
  1a55: jb     0x1a78                                         ; startNanos < targetNanos -> PreciseSleepFromNanos
  ; otherwise returns immediately with 0 epilogue calls

Tested

  • CPU: AMD Ryzen 7 7700 (x86_64, Zen 4)
  • Windows 10 (x86_64, MinGW-w64 GCC 15.2): Built precise_wait_tests, libkernel, libSceAudio3d, libSceAudioIn and ran ctest --test-dir build -R precise_wait --output-on-failure (Passed, 0.13 sec).
  • Linux (x86_64, Docker anyps5-env:arch GCC 16.2.1 & anyps5-env:ubuntu GCC 11.4.0): Compiled and ran core/libs/tests/PreciseWait.cpp (Passed).
  • macOS (Apple M2 Max, arm64 native & x86_64 Rosetta, Apple Clang 21.0.0 libc++): Verified PreciseSleepUntil(now + 1ms) (1.10–1.17 ms vs 1.15–1.23 ms on main) and 20/20 runs of core/libs/tests/PreciseWait.cpp (0/20 failures vs 20/20 early-return failures on main).
  • Conventions: python3 tools/check_conventions.py --base origin/main (All conventions checks passed).

1. CPU Cycle Benchmark (__rdtscp on AMD Ryzen 7 7700, Before vs After on the same machine, pinned to core 0)

Scenario Platform / Environment main (post-#5827) PR (#10 + #15 + Linux fast-path) Delta (Cycles / %) Hardware / Assembly Change
PreciseSleepUntil(past) (steady_clock::time_point [ns]) Windows (MinGW-w64 GCC) p50: 416 cyc
p90: 416 cyc
mean: 447.6 cyc (115.3 ns)
p50: 156 cyc
p90: 156 cyc
mean: 154.8 cyc (59.1 ns)
−260 cyc (−62.5%, 2.67× faster) 1 QPC read instead of 3 QPC reads (+ 6 idiv in libwinpthread)
PreciseSleepUntil(past) (steady_clock::time_point [ns]) Linux (ArchLinux GCC 16.2) p50: 364 cyc
p90: 364 cyc
mean: 351.9 cyc (100.4 ns)
p50: 156 cyc
p90: 156 cyc
mean: 165.0 cyc (61.5 ns)
−208 cyc (−57.1%, 2.33× faster) 1 clock_gettime instead of 3 clock_gettime
PreciseSleepUntil(past) (steady_clock::time_point [ns]) Linux (Ubuntu GCC 11.4) p50: 364 cyc
p90: 364 cyc
mean: 349.8 cyc (98.1 ns)
p50: 156 cyc
p90: 208 cyc
mean: 180.6 cyc (64.5 ns)
−208 cyc (−57.1%, 2.33× faster) 1 clock_gettime instead of 3 clock_gettime
PreciseSleepUntil(past) (time_point<steady_clock, us>) Windows (MinGW-w64 GCC) p50: 416 cyc
p90: 416 cyc
mean: 409.7 cyc (108.0 ns)
p50: 156 cyc
p90: 156 cyc
mean: 154.6 cyc (72.7 ns)
−260 cyc (−62.5%, 2.67× faster) 1 QPC read, 0 divisions (* 10 via add + lea)
PreciseSleepUntil(past) (time_point<steady_clock, us>) Linux (ArchLinux / Ubuntu) p50: 364 cyc
p90: 364 cyc
p50: 156 cyc
p90: 156–208 cyc
−208 cyc (−57.1%, 2.33× faster) 1 clock_gettime instead of 3 clock_gettime
PreciseSleepUntil(epoch <= 0) (steady_clock::time_point{}) Windows & Linux p50: 364–416 cyc
mean: 349–427 cyc
p50: 52 cyc
mean: 67.9–69.4 cyc
−312..−364 cyc (−85.7%..−87.5%) 0 clock reads (early return on rawDeadline <= 0)
Critical-path math after QPC (steady_clock [ns]) Windows (x86_64) p50: 11.02 cyc
p90: 11.13 cyc
p50: 4.89 cyc
p90: 4.99 cyc
−6.13 cyc (−55.6%) 1 sub after QPC instead of imul 100 + 128-bit mul + shr + add
Full tick math (time_point<steady_clock, us>) Windows (x86_64) p50: 14.04 cyc
p90: 14.14 cyc
p50: 5.10 cyc
p90: 5.10 cyc
−8.94 cyc (−63.7%) 128-bit / 100 division eliminated completely

2. Per-Call Latency, Total Cycles & Wakeup Overshoot (main after #5827 vs PR)

Call Platform main (avg / p50 / p90 / p99 / p50 cycles / overshoot) PR (avg / p50 / p90 / p99 / p50 cycles / overshoot)
PreciseSleepUntil(+500 ns) Windows (MinGW-w64) 0.50 us / 0.50 us / 0.50 us / 0.50 us / 2704 cyc 0.50 us / 0.50 us / 0.50 us / 0.50 us / 2600 cyc (−104 cyc exit overhead)
PreciseSleepUntil(+1 us) Windows (MinGW-w64) 1.00 us / 1.00 us / 1.00 us / 1.00 us / 5356 cyc 1.00 us / 1.00 us / 1.00 us / 1.00 us / 5200 cyc (−156 cyc exit overhead)
PreciseSleepUntil(+50 us) Windows (MinGW-w64) 52.15 us / 50.00 us / 50.10 us / 157.00 us / 260156 cyc (p90: 260572 cyc) 52.29 us / 50.00 us / 50.00 us / 165.80 us / 260000 cyc (p90: 260104 cyc, −468 cyc p90)
PreciseSleepUntil(+50 us) Linux (Ubuntu) 51.33 us / 50.10 us / 56.30 us / 98.70 us / overshoot p50 101 ns (mean 1331 ns) 50.98 us / 50.00 us / 55.40 us / 76.10 us / overshoot p50 2 ns (mean 982 ns, −26.2%)
PreciseSleepUntil(+1000 us) Windows (MinGW-w64) 1046.36 us / 1018.20 us / 1103.60 us / 2120.90 us / overshoot mean 46.36 us 1024.52 us / 1000.00 us / 1117.40 us / 1439.90 us / overshoot mean 24.52 us (−47.1%)
PreciseSleepUntil(+1000 us) Linux (ArchLinux) 1006.40 us / 1006.74 us / 1012.24 us / 1038.24 us / overshoot p50 6736 ns (mean 6399 ns) 1003.96 us / 1002.24 us / 1009.54 us / 1064.44 us / overshoot p50 2236 ns (mean 3960 ns, −38.1%)
PreciseSleepUntil(+1000 us) Linux (Ubuntu) 1006.52 us / 1005.83 us / 1011.33 us / 1059.43 us / overshoot p50 5832 ns (mean 6525 ns) 1004.46 us / 1003.43 us / 1010.53 us / 1027.93 us / overshoot p50 3432 ns (mean 4462 ns, −31.6%)

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4881066346 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6620). Originally posted by [hamb3r](https://github.com/hamb3r) on 2026-10-15T23:14:54Z. --- ### What - Extract `PreciseQpcFrequency()` so `PreciseSleepFromCounterWithTimer` and `PreciseSleepUntil` share the cached `QueryPerformanceFrequency` value on Windows. - Add a `std::chrono::steady_clock` fast path in `PreciseSleepUntil` on both Windows (`PreciseQpcFrequency() == 10000000ULL`, `10 MHz` QPC) and POSIX/Linux (`PreciseMonotonicNanos()`) that converts `deadline.time_since_epoch()` to hardware clock ticks **before** sampling the hardware clock and delegates directly to `PreciseSleepFromCounter` / `PreciseSleepFromNanos`: 1. **Eliminates 2 redundant `steady_clock::now()` reads per call:** On current `main`, `PreciseSleepUntil` reads the hardware clock (`QueryPerformanceCounter` on Windows, `PreciseMonotonicNanos` on POSIX), then immediately calls `TClock::now()` (which on Windows MinGW-w64 `libstdc++` calls `libwinpthread!clock_gettime(CLOCK_MONOTONIC)` -> uncached `QueryPerformanceFrequency` + `QueryPerformanceCounter` + three 64-bit `idiv` instructions, and on Linux calls `steady_clock::now()@PLT`), and then calls `TClock::now()` a third time in the post-wait epilogue loop — performing **3 hardware clock reads** even when the deadline has already expired. 2. **Eliminates $T_0$ vs $T_1$ sampling skew:** On `main`, the initial hardware counter is sampled at $T_0$ and `now = TClock::now()` is sampled at $T_1 > T_0$. Computing `remaining = deadline - now` ($deadline - T_1$) and adding it to the counter sampled at $T_0$ causes `PreciseSleepFromCounter` / `PreciseSleepFromNanos` to wake up at $T_0 + (deadline - T_1) = deadline - (T_1 - T_0)$, systematically undershooting `deadline` and forcing execution into the `for (auto current = TClock::now(); ...)` epilogue loop. 3. **Eliminates `* 100` and 128-bit `/ 100` division after `QueryPerformanceCounter` on Windows (`10 MHz`):** By the integer identity $$\left\lceil \frac{\text{deadlineNs} - 100 \cdot \text{counter}}{100} \right\rceil = \left\lceil \frac{\text{deadlineNs}}{100} \right\rceil - \text{counter}$$ checking `if (rawDeadline <= 0) [[unlikely]] { return; }` and precomputing `targetHns` before `QueryPerformanceCounter(&counter)` removes `imul` (`* 100`), 128-bit `mul 0x28f5c28f5c28f5c3` (`/ 100`), and `add` from the timing-critical window after sampling the counter, leaving a single `sub` instruction (`targetHns - nowTicks`). For coarser `time_point` durations (such as `microseconds`), division is eliminated completely (`add + lea` for `* 10`). - Align `PreciseMonotonicNanos()` on Apple `libc++` (`__APPLE__ && _LIBCPP_VERSION && CLOCK_MONOTONIC_RAW`) to use `clock_gettime(CLOCK_MONOTONIC_RAW, &ts)` so it shares the exact clock source and sub-microsecond resolution of `libc++`'s `std::chrono::steady_clock::now()` (which also fixes `PreciseSleepUs` returning up to `1 us` early against `steady_clock` on macOS due to `CLOCK_MONOTONIC`'s `1000 ns` resolution), and gate the non-Windows `steady_clock` fast path to configurations with guaranteed matching clock sources. - Add unit test coverage in `core/libs/tests/PreciseWait.cpp` for zero-epoch (`steady_clock::time_point{}`) and coarse-duration (`time_point<steady_clock, microseconds>`) deadlines. <details> <summary><code>llvm-objdump -d --x86-asm-syntax=intel</code> (Windows x64 <code>PreciseSleepUntil&lt;steady_clock&gt;</code>: Before vs After)</summary> **Before (`main`: calls `QueryPerformanceCounter`, then calls `steady_clock::now()`, performs 128-bit `/ 100` division after QPC, and loops on `steady_clock::now()` again at exit):** ```asm 14: call qword ptr [rip + __imp_QueryPerformanceCounter] ; QPC read #1 (T0) 1a: call std::chrono::steady_clock::now ; QPC read #2 (T1) 25: mov rcx, qword ptr [rsi] 28: sub rcx, rax ; deadlineNs - nowNs 2b: jle 0x5b 2d: add rcx, 0x63 31: movabs rax, 0x28f5c28f5c28f5c3 3b: mul rcx ; 128-bit / 100 AFTER clock read! 3e: shr rdx, 0x6 42: mov rcx, qword ptr [rsp + 0x38] 47: call PreciseSleepFromCounter ; wakes up (T1 - T0) before deadline! 5b: call std::chrono::steady_clock::now ; QPC read #3+ in epilogue loop 60: cmp rax, qword ptr [rsi] 63: jge 0x7c ``` **After (`PR`: 0 calls to `steady_clock::now()`; `targetHns` precomputed before `QueryPerformanceCounter`; only `mov + sub + jbe` after `QueryPerformanceCounter`):** ```asm 1c: mov rax, qword ptr [rcx] 1f: test rax, rax 22: jle 0xdc ; rawDeadline <= 0 -> immediate return (0 QPC reads!) 28: add rax, 0x63 2c: shr rax, 0x2 30: movabs rcx, 0x28f5c28f5c28f5c3 3a: mul rcx ; targetHns precomputed BEFORE QPC read! 3d: mov rsi, rdx 40: shr rsi, 0x2 44: lea rcx, [rsp + 0x40] 49: call qword ptr [rip + __imp_QueryPerformanceCounter] ; single QPC read! 4f: mov rax, qword ptr [rsp + 0x40] 54: mov rcx, rsi 57: sub rcx, rax ; remainingTicks = targetHns - nowTicks (1 instruction!) 5a: jbe 0xdc ; already reached -> immediate return ``` **After (for `time_point<steady_clock, microseconds>`: 0 divisions anywhere in the function):** ```asm 28: add rax, rax 2b: lea rsi, [rax + 4*rax] ; targetHns = rawDeadlineUs * 10 (2 instructions!) 2f: lea rcx, [rsp + 0x40] 34: call qword ptr [rip + __imp_QueryPerformanceCounter] 3a: mov rax, qword ptr [rsp + 0x40] 3f: mov rcx, rsi 42: sub rcx, rax ; remainingTicks = targetHns - nowTicks 45: jbe 0xc7 ``` </details> <details> <summary><code>objdump -d -M intel</code> (Linux x86_64 <code>PreciseSleepUntil&lt;steady_clock&gt;</code>: Before vs After)</summary> **Before (`main`: calls `clock_gettime`, then immediately calls `steady_clock::now()@PLT`, and calls `steady_clock::now()@PLT` again in the epilogue loop):** ```asm 1bee: mov edi, 0x1 1bf3: call clock_gettime@plt ; clock read #1: PreciseMonotonicNanos() (T0) 1bf8: mov rbp, QWORD PTR [rsp+0x10] 1bfd: mov r12, QWORD PTR [rsp+0x18] 1c02: call std::chrono::_V2::steady_clock::now()@plt ; clock read #2: steady_clock::now() (T1) 1c07: mov rdx, QWORD PTR [rbx] 1c0a: cmp rax, rdx 1c0d: jge 0x1cf0 ; -> clock read #3: steady_clock::now()@plt in epilogue ``` **After (`PR`: 0 calls to `steady_clock::now()@PLT`; single `clock_gettime` call):** ```asm 1a24: test rdi, rdi 1a27: jle 0x1a5c ; rawDeadline <= 0 -> immediate return (0 clock reads!) 1a35: lea rsi, [rsp+0x10] 1a3a: mov edi, 0x1 1a3f: call clock_gettime@plt ; single clock read! 1a44: imul rax, QWORD PTR [rsp+0x10], 0x3b9aca00 1a4d: add rax, QWORD PTR [rsp+0x18] 1a52: cmp rax, rbx 1a55: jb 0x1a78 ; startNanos < targetNanos -> PreciseSleepFromNanos ; otherwise returns immediately with 0 epilogue calls ``` </details> --- ### Tested - **CPU:** AMD Ryzen 7 7700 (`x86_64`, Zen 4) - **Windows 10 (`x86_64`, MinGW-w64 GCC 15.2):** Built `precise_wait_tests`, `libkernel`, `libSceAudio3d`, `libSceAudioIn` and ran `ctest --test-dir build -R precise_wait --output-on-failure` (`Passed, 0.13 sec`). - **Linux (`x86_64`, Docker `anyps5-env:arch` GCC 16.2.1 & `anyps5-env:ubuntu` GCC 11.4.0):** Compiled and ran `core/libs/tests/PreciseWait.cpp` (`Passed`). - **macOS (`Apple M2 Max`, `arm64` native & `x86_64` Rosetta, Apple Clang 21.0.0 `libc++`):** Verified `PreciseSleepUntil(now + 1ms)` (`1.10–1.17 ms` vs `1.15–1.23 ms` on `main`) and 20/20 runs of `core/libs/tests/PreciseWait.cpp` (`0/20` failures vs `20/20` early-return failures on `main`). - **Conventions:** `python3 tools/check_conventions.py --base origin/main` (`All conventions checks passed`). #### 1. CPU Cycle Benchmark (`__rdtscp` on AMD Ryzen 7 7700, Before vs After on the same machine, pinned to core 0) | Scenario | Platform / Environment | `main` (post-#5827) | PR (`#10 + #15` + Linux fast-path) | Delta (Cycles / %) | Hardware / Assembly Change | |---|---|---|---|---|---| | `PreciseSleepUntil(past)` (`steady_clock::time_point` [ns]) | Windows (`MinGW-w64 GCC`) | `p50: 416 cyc`<br>`p90: 416 cyc`<br>`mean: 447.6 cyc (115.3 ns)` | `p50: 156 cyc`<br>`p90: 156 cyc`<br>`mean: 154.8 cyc (59.1 ns)` | **−260 cyc (`−62.5%`, 2.67× faster)** | **1 QPC read** instead of **3 QPC reads** (+ 6 `idiv` in `libwinpthread`) | | `PreciseSleepUntil(past)` (`steady_clock::time_point` [ns]) | Linux (`ArchLinux GCC 16.2`) | `p50: 364 cyc`<br>`p90: 364 cyc`<br>`mean: 351.9 cyc (100.4 ns)` | `p50: 156 cyc`<br>`p90: 156 cyc`<br>`mean: 165.0 cyc (61.5 ns)` | **−208 cyc (`−57.1%`, 2.33× faster)** | **1 `clock_gettime`** instead of **3 `clock_gettime`** | | `PreciseSleepUntil(past)` (`steady_clock::time_point` [ns]) | Linux (`Ubuntu GCC 11.4`) | `p50: 364 cyc`<br>`p90: 364 cyc`<br>`mean: 349.8 cyc (98.1 ns)` | `p50: 156 cyc`<br>`p90: 208 cyc`<br>`mean: 180.6 cyc (64.5 ns)` | **−208 cyc (`−57.1%`, 2.33× faster)** | **1 `clock_gettime`** instead of **3 `clock_gettime`** | | `PreciseSleepUntil(past)` (`time_point<steady_clock, us>`) | Windows (`MinGW-w64 GCC`) | `p50: 416 cyc`<br>`p90: 416 cyc`<br>`mean: 409.7 cyc (108.0 ns)` | `p50: 156 cyc`<br>`p90: 156 cyc`<br>`mean: 154.6 cyc (72.7 ns)` | **−260 cyc (`−62.5%`, 2.67× faster)** | **1 QPC read**, 0 divisions (`* 10` via `add + lea`) | | `PreciseSleepUntil(past)` (`time_point<steady_clock, us>`) | Linux (`ArchLinux` / `Ubuntu`) | `p50: 364 cyc`<br>`p90: 364 cyc` | `p50: 156 cyc`<br>`p90: 156–208 cyc` | **−208 cyc (`−57.1%`, 2.33× faster)** | **1 `clock_gettime`** instead of **3 `clock_gettime`** | | `PreciseSleepUntil(epoch <= 0)` (`steady_clock::time_point{}`) | Windows & Linux | `p50: 364–416 cyc`<br>`mean: 349–427 cyc` | `p50: 52 cyc`<br>`mean: 67.9–69.4 cyc` | **−312..−364 cyc (`−85.7%..−87.5%`)** | **0 clock reads** (early return on `rawDeadline <= 0`) | | Critical-path math **after** `QPC` (`steady_clock` [ns]) | Windows (`x86_64`) | `p50: 11.02 cyc`<br>`p90: 11.13 cyc` | `p50: 4.89 cyc`<br>`p90: 4.99 cyc` | **−6.13 cyc (`−55.6%`)** | **1 `sub`** after QPC instead of `imul 100` + 128-bit `mul` + `shr` + `add` | | Full tick math (`time_point<steady_clock, us>`) | Windows (`x86_64`) | `p50: 14.04 cyc`<br>`p90: 14.14 cyc` | `p50: 5.10 cyc`<br>`p90: 5.10 cyc` | **−8.94 cyc (`−63.7%`)** | 128-bit `/ 100` division eliminated completely | #### 2. Per-Call Latency, Total Cycles & Wakeup Overshoot (`main` after #5827 vs PR) | Call | Platform | `main` (avg / p50 / p90 / p99 / p50 cycles / overshoot) | PR (avg / p50 / p90 / p99 / p50 cycles / overshoot) | |---|---|---|---| | `PreciseSleepUntil(+500 ns)` | Windows (`MinGW-w64`) | `0.50 us` / `0.50 us` / `0.50 us` / `0.50 us` / **`2704 cyc`** | `0.50 us` / `0.50 us` / `0.50 us` / `0.50 us` / **`2600 cyc` (−104 cyc exit overhead)** | | `PreciseSleepUntil(+1 us)` | Windows (`MinGW-w64`) | `1.00 us` / `1.00 us` / `1.00 us` / `1.00 us` / **`5356 cyc`** | `1.00 us` / `1.00 us` / `1.00 us` / `1.00 us` / **`5200 cyc` (−156 cyc exit overhead)** | | `PreciseSleepUntil(+50 us)` | Windows (`MinGW-w64`) | `52.15 us` / `50.00 us` / `50.10 us` / `157.00 us` / **`260156 cyc`** (`p90: 260572 cyc`) | `52.29 us` / `50.00 us` / `50.00 us` / `165.80 us` / **`260000 cyc`** (`p90: 260104 cyc`, **−468 cyc p90**) | | `PreciseSleepUntil(+50 us)` | Linux (`Ubuntu`) | `51.33 us` / `50.10 us` / `56.30 us` / `98.70 us` / **overshoot p50 `101 ns` (mean `1331 ns`)** | `50.98 us` / `50.00 us` / `55.40 us` / `76.10 us` / **overshoot p50 `2 ns` (mean `982 ns`, −26.2%)** | | `PreciseSleepUntil(+1000 us)` | Windows (`MinGW-w64`) | `1046.36 us` / `1018.20 us` / `1103.60 us` / `2120.90 us` / **overshoot mean `46.36 us`** | `1024.52 us` / `1000.00 us` / `1117.40 us` / `1439.90 us` / **overshoot mean `24.52 us` (−47.1%)** | | `PreciseSleepUntil(+1000 us)` | Linux (`ArchLinux`) | `1006.40 us` / `1006.74 us` / `1012.24 us` / `1038.24 us` / **overshoot p50 `6736 ns` (mean `6399 ns`)** | `1003.96 us` / `1002.24 us` / `1009.54 us` / `1064.44 us` / **overshoot p50 `2236 ns` (mean `3960 ns`, −38.1%)** | | `PreciseSleepUntil(+1000 us)` | Linux (`Ubuntu`) | `1006.52 us` / `1005.83 us` / `1011.33 us` / `1059.43 us` / **overshoot p50 `5832 ns` (mean `6525 ns`)** | `1004.46 us` / `1003.43 us` / `1010.53 us` / `1027.93 us` / **overshoot p50 `3432 ns` (mean `4462 ns`, −31.6%)** | ### Checklist - [x] Based on current `main`; no other open PR implements the same functions - [x] One topic per PR; follow-ups go in a new PR - [x] No comments in code except [technical debt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/CONVENTIONS.md) - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed under Silent stubs in their library's [technical debt](https://github.com/boykopovar/AnyPS5/tree/main/docs/dev/debt) file - [x] No notes, investigation `.md` files or images added to the repository (attach them to this PR) - [x] New third-party code is a submodule built from source - [x] Generic behaviour, not specific to one title - [x] Depends on: none - [x] Unblocks: none - [x] GPUs tested: n/a - [x] AI-assisted: yes
hamb3r commented 2026-10-15 23:15:04 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by hamb3r on 2026-10-15T23:15:04Z.


cc @adriadam10 @CnRJay — follow-up to #5827, would appreciate your review when you have a moment!

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6204246801 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6620#issuecomment-6204246801). Originally posted by [hamb3r](https://github.com/hamb3r) on 2026-10-15T23:15:04Z. --- cc @adriadam10 @CnRJay — follow-up to #5827, would appreciate your review when you have a moment!
MarcZX10 commented 2026-10-15 23:23:27 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-15T23:23:27Z.


The non-Windows fast path assumes steady_clock::time_since_epoch() and CLOCK_MONOTONIC share the same epoch/rate, then compares their absolute nanosecond values. On macOS, libc++ implements steady_clock with CLOCK_MONOTONIC_RAW (see llvm-project/libcxx/src/chrono.cpp, __libcpp_steady_clock_now), while this helper calls clock_gettime(CLOCK_MONOTONIC). Those are distinct clocks, so the absolute comparison can mis-size the sleep and turn the fast path into an unexpectedly long wait or spin. Could this keep the remaining-duration calculation from TClock::now() on platforms where the clock source is not guaranteed to match, or use a platform clock source that is explicitly the same as steady_clock? The final TClock::now() loop prevents an early return but does not correct an oversized sleep.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6204355808 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6620#issuecomment-6204355808). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-15T23:23:27Z. --- The non-Windows fast path assumes `steady_clock::time_since_epoch()` and `CLOCK_MONOTONIC` share the same epoch/rate, then compares their absolute nanosecond values. On macOS, libc++ implements `steady_clock` with `CLOCK_MONOTONIC_RAW` (see `llvm-project/libcxx/src/chrono.cpp`, `__libcpp_steady_clock_now`), while this helper calls `clock_gettime(CLOCK_MONOTONIC)`. Those are distinct clocks, so the absolute comparison can mis-size the sleep and turn the fast path into an unexpectedly long wait or spin. Could this keep the remaining-duration calculation from `TClock::now()` on platforms where the clock source is not guaranteed to match, or use a platform clock source that is explicitly the same as `steady_clock`? The final `TClock::now()` loop prevents an early return but does not correct an oversized sleep.
github-actions[bot] commented 2026-10-15 23:30:19 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by github-actions[bot] on 2026-10-15T23:30:19Z.


Some comparisons could not be completed because a pull request conflicts with the base branch. Review these shared files manually before concluding that there is no overlap.

Pull request Shared files not compared
PR 6044 core/libs/tests/PreciseWait.cpp
PR 7332 core/libs/prx/libc/include/PreciseWait.hpp
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6204444218 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6620#issuecomment-6204444218). Originally posted by [github-actions[bot]](https://github.com/apps/github-actions) on 2026-10-15T23:30:19Z. --- <!-- pr-overlap --> Some comparisons could not be completed because a pull request conflicts with the base branch. Review these shared files manually before concluding that there is no overlap. | Pull request | Shared files not compared | |---|---| | [PR 6044](https://www.github.com/boykopovar/AnyPS5/pull/6044) | `core/libs/tests/PreciseWait.cpp` | | [PR 7332](https://www.github.com/boykopovar/AnyPS5/pull/7332) | `core/libs/prx/libc/include/PreciseWait.hpp` |
hamb3r commented 2026-10-15 23:54:45 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by hamb3r on 2026-10-15T23:54:45Z.


Great catch @MarcZX100, thank you!

I checked the upstream steady_clock::now() implementations across libc++ (libcxx/src/chrono.cpp) and libstdc++ (libstdc++-v3/src/c++11/chrono.cc):

  1. Apple (libc++, libcxx/src/chrono.cpp):
    #  if defined(__APPLE__)
    static steady_clock::time_point __libcpp_steady_clock_now() {
      struct timespec tp;
      if (0 != clock_gettime(CLOCK_MONOTONIC_RAW, &tp))
        std::__throw_system_error(errno, "clock_gettime(CLOCK_MONOTONIC_RAW) failed");
      return steady_clock::time_point(seconds(tp.tv_sec) + nanoseconds(tp.tv_nsec));
    }
    
    Whereas PreciseMonotonicNanos() in core/libs/prx/libc/include/PreciseWait.hpp was unconditionally calling:
    clock_gettime(CLOCK_MONOTONIC, &ts);
    
  2. Linux (libstdc++-v3/src/c++11/chrono.cc and libcxx/src/chrono.cpp under _LIBCPP_HAS_CLOCK_GETTIME):
    Both libstdc++ and libc++ call clock_gettime(CLOCK_MONOTONIC, &tp) and construct seconds(tp.tv_sec) + nanoseconds(tp.tv_nsec), matching PreciseMonotonicNanos().

Addressed in a7b8a697d (core/libs/prx/libc/include/PreciseWait.hpp):

  • In PreciseMonotonicNanos(), use clock_gettime(CLOCK_MONOTONIC_RAW, &ts) when defined(__APPLE__) && defined(_LIBCPP_VERSION) && defined(CLOCK_MONOTONIC_RAW) so it uses the exact same clock source as libc++'s std::chrono::steady_clock::now() on macOS (while keeping CLOCK_MONOTONIC on Linux where PreciseSleepFromNanosWithSlack uses clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, ...)).
  • In PreciseSleepUntil(), guard the non-Windows steady_clock fast path with:
    #if (defined(__linux__) && (defined(__GLIBCXX__) || (defined(_LIBCPP_VERSION) && !defined(_LIBCPP_HAS_TIMESPEC_GET)))) || \
        (defined(__APPLE__) && defined(_LIBCPP_VERSION) && defined(CLOCK_MONOTONIC_RAW))
    
    so any platform or standard library configuration where the clock source is not explicitly guaranteed to match keeps the TClock::now() remaining-duration calculation.
Platform / Standard Library std::chrono::steady_clock::now() Source PreciseWait Hardware Clock Source (Before a7b8a697d) PreciseWait Hardware Clock Source (After a7b8a697d) PreciseSleepUntil<steady_clock> Path
Windows (_WIN32, 10 MHz QPC) QueryPerformanceCounter QueryPerformanceCounter QueryPerformanceCounter (unchanged) Direct targetHns - nowTicks fast path
Linux (__linux__, libstdc++ / libc++) CLOCK_MONOTONIC CLOCK_MONOTONIC CLOCK_MONOTONIC (unchanged) Direct targetNanos - startNanos fast path
macOS (__APPLE__, libc++) CLOCK_MONOTONIC_RAW CLOCK_MONOTONIC (mismatched) CLOCK_MONOTONIC_RAW (aligned) Direct targetNanos - startNanos fast path
Other POSIX / unknown STL Platform-dependent CLOCK_MONOTONIC CLOCK_MONOTONIC Fallback to deadline - TClock::now()
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6204753833 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6620#issuecomment-6204753833). Originally posted by [hamb3r](https://github.com/hamb3r) on 2026-10-15T23:54:45Z. --- Great catch @MarcZX100, thank you! I checked the upstream `steady_clock::now()` implementations across `libc++` (`libcxx/src/chrono.cpp`) and `libstdc++` (`libstdc++-v3/src/c++11/chrono.cc`): 1. **Apple (`libc++`, `libcxx/src/chrono.cpp`):** ```cpp # if defined(__APPLE__) static steady_clock::time_point __libcpp_steady_clock_now() { struct timespec tp; if (0 != clock_gettime(CLOCK_MONOTONIC_RAW, &tp)) std::__throw_system_error(errno, "clock_gettime(CLOCK_MONOTONIC_RAW) failed"); return steady_clock::time_point(seconds(tp.tv_sec) + nanoseconds(tp.tv_nsec)); } ``` Whereas `PreciseMonotonicNanos()` in `core/libs/prx/libc/include/PreciseWait.hpp` was unconditionally calling: ```cpp clock_gettime(CLOCK_MONOTONIC, &ts); ``` 2. **Linux (`libstdc++-v3/src/c++11/chrono.cc` and `libcxx/src/chrono.cpp` under `_LIBCPP_HAS_CLOCK_GETTIME`):** Both `libstdc++` and `libc++` call `clock_gettime(CLOCK_MONOTONIC, &tp)` and construct `seconds(tp.tv_sec) + nanoseconds(tp.tv_nsec)`, matching `PreciseMonotonicNanos()`. Addressed in a7b8a697d (`core/libs/prx/libc/include/PreciseWait.hpp`): - In `PreciseMonotonicNanos()`, use `clock_gettime(CLOCK_MONOTONIC_RAW, &ts)` when `defined(__APPLE__) && defined(_LIBCPP_VERSION) && defined(CLOCK_MONOTONIC_RAW)` so it uses the exact same clock source as `libc++`'s `std::chrono::steady_clock::now()` on macOS (while keeping `CLOCK_MONOTONIC` on Linux where `PreciseSleepFromNanosWithSlack` uses `clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, ...)`). - In `PreciseSleepUntil()`, guard the non-Windows `steady_clock` fast path with: ```cpp #if (defined(__linux__) && (defined(__GLIBCXX__) || (defined(_LIBCPP_VERSION) && !defined(_LIBCPP_HAS_TIMESPEC_GET)))) || \ (defined(__APPLE__) && defined(_LIBCPP_VERSION) && defined(CLOCK_MONOTONIC_RAW)) ``` so any platform or standard library configuration where the clock source is not explicitly guaranteed to match keeps the `TClock::now()` remaining-duration calculation. | Platform / Standard Library | `std::chrono::steady_clock::now()` Source | `PreciseWait` Hardware Clock Source (Before a7b8a697d) | `PreciseWait` Hardware Clock Source (After a7b8a697d) | `PreciseSleepUntil<steady_clock>` Path | |---|---|---|---|---| | **Windows** (`_WIN32`, `10 MHz` QPC) | `QueryPerformanceCounter` | `QueryPerformanceCounter` | `QueryPerformanceCounter` (unchanged) | Direct `targetHns - nowTicks` fast path | | **Linux** (`__linux__`, `libstdc++` / `libc++`) | `CLOCK_MONOTONIC` | `CLOCK_MONOTONIC` | `CLOCK_MONOTONIC` (unchanged) | Direct `targetNanos - startNanos` fast path | | **macOS** (`__APPLE__`, `libc++`) | `CLOCK_MONOTONIC_RAW` | `CLOCK_MONOTONIC` *(mismatched)* | **`CLOCK_MONOTONIC_RAW` (aligned)** | Direct `targetNanos - startNanos` fast path | | **Other POSIX / unknown STL** | Platform-dependent | `CLOCK_MONOTONIC` | `CLOCK_MONOTONIC` | Fallback to `deadline - TClock::now()` |
MarcZX10 commented 2026-10-16 00:35:59 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-16T00:35:59Z.


Thanks for aligning the macOS clock source and gating the absolute-deadline fast path to configurations where the source is known. I rechecked the updated path: macOS uses the same RAW source as libc++ and relative nanosleep before the final deadline check, while other unknown POSIX configurations use the duration-based fallback. That resolves my clock-mismatch concern; I did not run the patch on macOS.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6205294937 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6620#issuecomment-6205294937). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-16T00:35:59Z. --- Thanks for aligning the macOS clock source and gating the absolute-deadline fast path to configurations where the source is known. I rechecked the updated path: macOS uses the same RAW source as libc++ and relative nanosleep before the final deadline check, while other unknown POSIX configurations use the duration-based fallback. That resolves my clock-mismatch concern; I did not run the patch on macOS.
jotitadev commented 2026-10-16 11:34:06 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-16T11:34:06Z.

Review: COMMENTED


Ran this on macOS, since the last commit is macOS-specific and nobody had run it there yet.

Machine: Apple M2 Max, macOS 27.2, Apple clang 21.0.0 (libc++), arm64 native and x86_64 under Rosetta. Head a7b8a697d, base main aff725bf6. Full main does not build on macOS, so I compiled PreciseWait.hpp standalone: core/libs/tests/PreciseWait.cpp plus a small repro that calls PreciseSleepUntil(steady_clock::now() + 1ms).

Clock sources on this machine. steady_clock::now() matches CLOCK_MONOTONIC_RAW to well under 1 µs. CLOCK_MONOTONIC runs 2208 ms behind it, and clock_getres reports 1000 ns for it, against 42 ns (arm64) and 1 ns (x86_64) for RAW. The new __APPLE__ && _LIBCPP_VERSION && CLOCK_MONOTONIC_RAW gate evaluates true on both architectures.

Repro, PreciseSleepUntil(now + 1ms), 3 calls per build, arm64 and x86_64 the same:

Revision Measured
main aff725bf6 1.15-1.23 ms
previous head 78ce0b836 2213-2214 ms
this head a7b8a697d 1.10-1.17 ms

So the clock mismatch @MarcZX100 described was real on macOS: the absolute-deadline fast path overslept by the full CLOCK_MONOTONIC vs RAW offset, here about 2.2 s per call. a7b8a697d fixes it.

core/libs/tests/PreciseWait.cpp, 20 runs per build with APS5_SKIP_TIMING_TESTS=1 (this skips the median bounds and keeps the "returned before its requested duration" checks):

Revision arm64 x86_64
main aff725bf6 20/20 fail 20/20 fail
this head a7b8a697d 0/20 fail 0/20 fail

On main the failures are PreciseSleepUs returned before its requested duration and PreciseSleepUs(50) returned before its requested duration. PreciseMonotonicNanos() there reads CLOCK_MONOTONIC, which has 1 µs resolution on macOS, while the test measures with steady_clock (RAW). Moving PreciseMonotonicNanos() to RAW also fixes this existing macOS failure. That fix is not mentioned in the description.

With the median bounds enabled, the strict 90 µs / 1500 µs medians missed on some runs. My machine had a load average of about 170 during these runs, so I don't treat those misses as a result either way.

Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5547212763 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6620#pullrequestreview-5547212763). Originally posted by [jotitadev](https://github.com/jotitadev) on 2026-10-16T11:34:06Z. **Review:** COMMENTED --- Ran this on macOS, since the last commit is macOS-specific and nobody had run it there yet. Machine: Apple M2 Max, macOS 27.2, Apple clang 21.0.0 (libc++), arm64 native and x86_64 under Rosetta. Head `a7b8a697d`, base `main` `aff725bf6`. Full `main` does not build on macOS, so I compiled `PreciseWait.hpp` standalone: `core/libs/tests/PreciseWait.cpp` plus a small repro that calls `PreciseSleepUntil(steady_clock::now() + 1ms)`. **Clock sources on this machine.** `steady_clock::now()` matches `CLOCK_MONOTONIC_RAW` to well under 1 µs. `CLOCK_MONOTONIC` runs 2208 ms behind it, and `clock_getres` reports 1000 ns for it, against 42 ns (arm64) and 1 ns (x86_64) for RAW. The new `__APPLE__ && _LIBCPP_VERSION && CLOCK_MONOTONIC_RAW` gate evaluates true on both architectures. **Repro, `PreciseSleepUntil(now + 1ms)`, 3 calls per build, arm64 and x86_64 the same:** | Revision | Measured | |---|---| | `main` `aff725bf6` | 1.15-1.23 ms | | previous head `78ce0b836` | 2213-2214 ms | | this head `a7b8a697d` | 1.10-1.17 ms | So the clock mismatch @MarcZX100 described was real on macOS: the absolute-deadline fast path overslept by the full `CLOCK_MONOTONIC` vs RAW offset, here about 2.2 s per call. `a7b8a697d` fixes it. **`core/libs/tests/PreciseWait.cpp`, 20 runs per build with `APS5_SKIP_TIMING_TESTS=1`** (this skips the median bounds and keeps the "returned before its requested duration" checks): | Revision | arm64 | x86_64 | |---|---|---| | `main` `aff725bf6` | 20/20 fail | 20/20 fail | | this head `a7b8a697d` | 0/20 fail | 0/20 fail | On `main` the failures are `PreciseSleepUs returned before its requested duration` and `PreciseSleepUs(50) returned before its requested duration`. `PreciseMonotonicNanos()` there reads `CLOCK_MONOTONIC`, which has 1 µs resolution on macOS, while the test measures with `steady_clock` (RAW). Moving `PreciseMonotonicNanos()` to RAW also fixes this existing macOS failure. That fix is not mentioned in the description. With the median bounds enabled, the strict 90 µs / 1500 µs medians missed on some runs. My machine had a load average of about 170 during these runs, so I don't treat those misses as a result either way. Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.
hamb3r commented 2026-10-16 12:03:14 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by hamb3r on 2026-10-16T12:03:14Z.


Thank you @jotitadev for testing this on an Apple M2 Max (arm64 native and x86_64 Rosetta) and verifying both the PreciseSleepUntil(now + 1ms) timings and the PreciseWait.cpp CLOCK_MONOTONIC_RAW resolution fix! Updated the PR description (What and Tested sections) to document this.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6215075927 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6620#issuecomment-6215075927). Originally posted by [hamb3r](https://github.com/hamb3r) on 2026-10-16T12:03:14Z. --- Thank you @jotitadev for testing this on an Apple M2 Max (`arm64` native and `x86_64` Rosetta) and verifying both the `PreciseSleepUntil(now + 1ms)` timings and the `PreciseWait.cpp` `CLOCK_MONOTONIC_RAW` resolution fix! Updated the PR description (`What` and `Tested` sections) to document this.
simonbronk commented 2026-10-16 13:39:35 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by simonbronk on 2026-10-16T13:39:35Z.


Independent Windows CPU check of head a7b8a697de5b8c67a6e8736f30f98fb4513631d7 against current main 82ddae75b6761757f3d3ba9c0723647469270f76 (AI-assisted, OpenAI Codex).

Compiled both unchanged PreciseWait.hpp / HostThreadLocal.hpp pairs, each ref's unchanged PreciseWait.cpp, and the same external probe. Windows x64, WinLibs GCC 15.2.0 r7 UCRT, -std=c++20 -O3 -DNDEBUG -static -pthread, no LTO. QPC reports 10 MHz. Alternating order: main/PR, PR/main, main/PR, PR/main; no affinity, priority, timer-resolution or power-policy changes.

All eight original-unit executions exit 0 with empty stdout/stderr; APS5_SKIP_TIMING_TESTS is unset. The external probe performs 400 calls per future-deadline mode per execution: +1 us with nanosecond duration, +50 us rounded up to microseconds, and +1 ms. Zero early returns in 9,600 future-deadline calls across both variants.

Median of four process-batch means, ns/call:

Already-expired deadline main PR
nanosecond duration 98.02 12.20
microsecond duration 102.04 12.28
zero epoch 104.50 0.70

Each expired-deadline batch contains 300,000 calls. The zero-epoch case is a compile-time-known argument and includes the benefit of simplifying that path; it is not the cost of a runtime deadline. All timings include the caller's loop. Future +1 us mean call time is 1.156 -> 1.062 us; +50 us and +1 ms results remain affected by scheduling noise, so I do not infer a general wakeup-latency improvement from them.

This supports the reduced expired-call overhead on another Windows setup. It is not a game/FPS, full native build, project CTest, GPU, other-OS, non-10-MHz QPC, full generic-duration, concurrency or timer-failure validation. Files were compiled directly outside the checkout; this does not test integration with all current-main consumers.

Reproduction: retrieve the three files above from each pinned ref, preserving prx/libc/include/ beneath each include directory; compile the probe below with g++ -std=c++20 -O3 -DNDEBUG -static -pthread -I<variant> probe.cpp -o probe.exe, and compile that variant's original PreciseWait.cpp with the same flags. Run in alternating order four times; median the per-process means. Raw results and runner are retained locally; the complete probe follows.

Independent probe source (same for both variants)
#include "prx/libc/include/PreciseWait.hpp"
#include <algorithm>
#include <cstdio>
#include <vector>
using Clock = std::chrono::steady_clock;
int main() {
    SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
    LARGE_INTEGER freq{};
    QueryPerformanceFrequency(&freq);
    std::printf("{\"qpc_hz\":%lld,\"samples\":[", freq.QuadPart);
    for (int mode = 0; mode < 6; ++mode) {
        const int count = mode < 3 ? 300000 : 400;
        const auto past = Clock::now() - std::chrono::seconds(1);
        std::vector<double> late;
        int early = 0;
        ULONG64 c0{}, c1{};
        QueryThreadCycleTime(GetCurrentThread(), &c0);
        const auto start = Clock::now();
        for (int i = 0; i < count; ++i) {
            if (mode == 0) PreciseSleepUntil(past);
            else if (mode == 1) PreciseSleepUntil(std::chrono::time_point_cast<std::chrono::microseconds>(past));
            else if (mode == 2) PreciseSleepUntil(Clock::time_point{});
            else {
                const auto deadline = Clock::now() + std::chrono::nanoseconds(mode == 3 ? 1000 : mode == 4 ? 50000 : 1000000);
                if (mode == 4) {
                    const auto coarse = std::chrono::ceil<std::chrono::microseconds>(deadline);
                    PreciseSleepUntil(coarse);
                    const auto end = Clock::now();
                    if (end < coarse) ++early;
                    late.push_back(std::chrono::duration<double,std::nano>(end-coarse).count());
                } else {
                    PreciseSleepUntil(deadline);
                    const auto end = Clock::now();
                    if (end < deadline) ++early;
                    late.push_back(std::chrono::duration<double,std::nano>(end-deadline).count());
                }
            }
        }
        const auto end = Clock::now();
        QueryThreadCycleTime(GetCurrentThread(), &c1);
        std::sort(late.begin(),late.end());
        std::printf("%s{\"mode\":%d,\"count\":%d,\"early\":%d,\"ns_per_call\":%.3f,\"cycles_per_call\":%.3f,\"late_p50_ns\":%.3f,\"late_p99_ns\":%.3f}",mode?",":"",mode,count,early,std::chrono::duration<double,std::nano>(end-start).count()/count,static_cast<double>(c1-c0)/count,late.empty()?0:late[late.size()/2],late.empty()?0:late[late.size()*99/100]);
        if (early) return 4;
    }
    std::puts("]}");
}
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6216754941 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6620#issuecomment-6216754941). Originally posted by [simonbronk](https://github.com/simonbronk) on 2026-10-16T13:39:35Z. --- Independent Windows CPU check of head `a7b8a697de5b8c67a6e8736f30f98fb4513631d7` against current main `82ddae75b6761757f3d3ba9c0723647469270f76` (AI-assisted, OpenAI Codex). Compiled both unchanged `PreciseWait.hpp` / `HostThreadLocal.hpp` pairs, each ref's unchanged `PreciseWait.cpp`, and the same external probe. Windows x64, WinLibs GCC 15.2.0 r7 UCRT, `-std=c++20 -O3 -DNDEBUG -static -pthread`, no LTO. QPC reports 10 MHz. Alternating order: main/PR, PR/main, main/PR, PR/main; no affinity, priority, timer-resolution or power-policy changes. All eight original-unit executions exit 0 with empty stdout/stderr; `APS5_SKIP_TIMING_TESTS` is unset. The external probe performs 400 calls per future-deadline mode per execution: +1 us with nanosecond duration, +50 us rounded up to microseconds, and +1 ms. **Zero early returns in 9,600 future-deadline calls across both variants.** Median of four process-batch means, ns/call: | Already-expired deadline | main | PR | |---|---:|---:| | nanosecond duration | 98.02 | 12.20 | | microsecond duration | 102.04 | 12.28 | | zero epoch | 104.50 | 0.70 | Each expired-deadline batch contains 300,000 calls. The zero-epoch case is a compile-time-known argument and includes the benefit of simplifying that path; it is not the cost of a runtime deadline. All timings include the caller's loop. Future +1 us mean call time is 1.156 -> 1.062 us; +50 us and +1 ms results remain affected by scheduling noise, so I do not infer a general wakeup-latency improvement from them. This supports the reduced expired-call overhead on another Windows setup. It is not a game/FPS, full native build, project CTest, GPU, other-OS, non-10-MHz QPC, full generic-duration, concurrency or timer-failure validation. Files were compiled directly outside the checkout; this does not test integration with all current-main consumers. Reproduction: retrieve the three files above from each pinned ref, preserving `prx/libc/include/` beneath each include directory; compile the probe below with `g++ -std=c++20 -O3 -DNDEBUG -static -pthread -I<variant> probe.cpp -o probe.exe`, and compile that variant's original `PreciseWait.cpp` with the same flags. Run in alternating order four times; median the per-process means. Raw results and runner are retained locally; the complete probe follows. <details><summary>Independent probe source (same for both variants)</summary> ```cpp #include "prx/libc/include/PreciseWait.hpp" #include <algorithm> #include <cstdio> #include <vector> using Clock = std::chrono::steady_clock; int main() { SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX); LARGE_INTEGER freq{}; QueryPerformanceFrequency(&freq); std::printf("{\"qpc_hz\":%lld,\"samples\":[", freq.QuadPart); for (int mode = 0; mode < 6; ++mode) { const int count = mode < 3 ? 300000 : 400; const auto past = Clock::now() - std::chrono::seconds(1); std::vector<double> late; int early = 0; ULONG64 c0{}, c1{}; QueryThreadCycleTime(GetCurrentThread(), &c0); const auto start = Clock::now(); for (int i = 0; i < count; ++i) { if (mode == 0) PreciseSleepUntil(past); else if (mode == 1) PreciseSleepUntil(std::chrono::time_point_cast<std::chrono::microseconds>(past)); else if (mode == 2) PreciseSleepUntil(Clock::time_point{}); else { const auto deadline = Clock::now() + std::chrono::nanoseconds(mode == 3 ? 1000 : mode == 4 ? 50000 : 1000000); if (mode == 4) { const auto coarse = std::chrono::ceil<std::chrono::microseconds>(deadline); PreciseSleepUntil(coarse); const auto end = Clock::now(); if (end < coarse) ++early; late.push_back(std::chrono::duration<double,std::nano>(end-coarse).count()); } else { PreciseSleepUntil(deadline); const auto end = Clock::now(); if (end < deadline) ++early; late.push_back(std::chrono::duration<double,std::nano>(end-deadline).count()); } } } const auto end = Clock::now(); QueryThreadCycleTime(GetCurrentThread(), &c1); std::sort(late.begin(),late.end()); std::printf("%s{\"mode\":%d,\"count\":%d,\"early\":%d,\"ns_per_call\":%.3f,\"cycles_per_call\":%.3f,\"late_p50_ns\":%.3f,\"late_p99_ns\":%.3f}",mode?",":"",mode,count,early,std::chrono::duration<double,std::nano>(end-start).count()/count,static_cast<double>(c1-c0)/count,late.empty()?0:late[late.size()/2],late.empty()?0:late[late.size()*99/100]); if (early) return 4; } std::puts("]}"); } ``` </details>
parl0v commented 2026-10-17 00:05:20 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by parl0v on 2026-10-17T00:05:20Z.


Data point from a CPU-bound scene on Windows: RTX 3060 12 GB (NVIDIA 617.42), i5-12400F, Windows 10 19045, MinGW GCC Release. Minecraft Dungeons II (PPSA16064 01.100.100), title screen, no input, 200 s rows, APS5_PROFILE_DRAW=1 APS5_PROFILE_GPU=1; main af0fff762 vs main + this PR, interleaved with five other PRs in one batch, two rounds. FPS is the mean of the last 10 [present] windows, GPU busy and idle gaps per frame over the last 8. This scene is CPU-bound on this machine (44-47 ms of idle gaps per frame).

libs FPS GPU busy idle gaps
main 6.61 / 6.76 105 / 104 ms 46 / 44 ms
+ this PR (a7b8a697d) 6.65 / 6.67 (-0.4 %) 104 / 105 ms 46 / 45 ms

Within the run-to-run spread (main itself moved 6.61 -> 6.76 between rounds), no regression, 0 fatal.

AI-assisted: yes (Claude Code)

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6227058056 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6620#issuecomment-6227058056). Originally posted by [parl0v](https://github.com/parl0v) on 2026-10-17T00:05:20Z. --- Data point from a CPU-bound scene on Windows: RTX 3060 12 GB (NVIDIA 617.42), i5-12400F, Windows 10 19045, MinGW GCC Release. Minecraft Dungeons II (PPSA16064 01.100.100), title screen, no input, 200 s rows, `APS5_PROFILE_DRAW=1 APS5_PROFILE_GPU=1`; `main` af0fff762 vs `main` + this PR, interleaved with five other PRs in one batch, two rounds. FPS is the mean of the last 10 `[present]` windows, GPU busy and idle gaps per frame over the last 8. This scene is CPU-bound on this machine (44-47 ms of idle gaps per frame). | libs | FPS | GPU busy | idle gaps | |---|---|---|---| | `main` | 6.61 / 6.76 | 105 / 104 ms | 46 / 44 ms | | + this PR (a7b8a697d) | 6.65 / 6.67 (-0.4 %) | 104 / 105 ms | 46 / 45 ms | Within the run-to-run spread (`main` itself moved 6.61 -> 6.76 between rounds), no regression, 0 fatal. AI-assisted: yes (Claude Code)
hamb3r commented 2026-10-17 22:45:51 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by hamb3r on 2026-10-17T22:45:51Z.


Hi @adriadam10 @oneandonlydean, hope you're doing well! Just bumping this so it doesn't get lost in the backlog. The changes are purely focused on optimizations, all checks are passing, and there are no merge conflicts. Would love to get your eyes on it when you have a few minutes!

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6242537922 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6620#issuecomment-6242537922). Originally posted by [hamb3r](https://github.com/hamb3r) on 2026-10-17T22:45:51Z. --- Hi @adriadam10 @oneandonlydean, hope you're doing well! Just bumping this so it doesn't get lost in the backlog. The changes are purely focused on optimizations, all checks are passing, and there are no merge conflicts. Would love to get your eyes on it when you have a few minutes!
mugurc commented 2026-10-18 14:00:17 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by mugurc on 2026-10-18T14:00:17Z.


A data point from macOS for the clock change here: Apple M5 Max, macOS 26.5.1, Apple clang 21, x86-64 under Rosetta 2, head a7b8a697d on main 47a266cf9 with my macOS series (the libraries do not link on macOS without it).

  • CLOCK_MONOTONIC counts whole microseconds on macOS (clock_getres reports 1000 ns, CLOCK_MONOTONIC_RAW 1 ns), so on main precise_wait fails with PreciseSleepUs(50) returned before its requested duration. With this pull request it passes those checks.
  • It then fails its 1500 µs bound (PreciseSleepUs(1500) median overslept target bound, medians 1.756 to 1.765 ms) in 7 runs of 8; in the other the test skipped the bound as a busy runner. macOS ends the nanosleep before the spin about a quarter of its length late for a thread without a time-constraint policy. In a standalone program a 1.4 ms nanosleep returned 360 µs late, and so did mach_wait_until and a thread with the user-interactive QoS class, as x86-64 and as arm64. Under THREAD_TIME_CONSTRAINT_POLICY it returned about 10 µs late. This does not come from this pull request: it would need a longer spin on macOS or real-time threads, and I have not changed either.
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6250795845 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6620#issuecomment-6250795845). Originally posted by [mugurc](https://github.com/mugurc) on 2026-10-18T14:00:17Z. --- A data point from macOS for the clock change here: Apple M5 Max, macOS 26.5.1, Apple clang 21, x86-64 under Rosetta 2, head a7b8a697d on `main` 47a266cf9 with my macOS series (the libraries do not link on macOS without it). - `CLOCK_MONOTONIC` counts whole microseconds on macOS (`clock_getres` reports 1000 ns, `CLOCK_MONOTONIC_RAW` 1 ns), so on `main` `precise_wait` fails with `PreciseSleepUs(50) returned before its requested duration`. With this pull request it passes those checks. - It then fails its 1500 µs bound (`PreciseSleepUs(1500) median overslept target bound`, medians 1.756 to 1.765 ms) in 7 runs of 8; in the other the test skipped the bound as a busy runner. macOS ends the `nanosleep` before the spin about a quarter of its length late for a thread without a time-constraint policy. In a standalone program a 1.4 ms `nanosleep` returned 360 µs late, and so did `mach_wait_until` and a thread with the user-interactive QoS class, as x86-64 and as arm64. Under `THREAD_TIME_CONSTRAINT_POLICY` it returned about 10 µs late. This does not come from this pull request: it would need a longer spin on macOS or real-time threads, and I have not changed either.
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
boykopovar/AnyPS5!6620
No description provided.