perf(libc): add Windows 24 MHz QPC fast path in PreciseSleepUntil #8097
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/8097"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Imported from boykopovar/AnyPS5. Originally posted by hamb3r on 2026-10-19T21:26:33Z.
What
std::chrono::steady_clockfast path inPreciseSleepUntilon Windows whenPreciseQpcFrequency() == 24000000ULL(24 MHzQPC, targeting Windows platforms where the hardware counter runs at 24 MHz, such as ARM64 systems clocked from a 24 MHz reference oscillator; cf. Microsoft STL PR #3832, which added a 24 MHz specialization to MSVC STL'ssteady_clock).PreciseDurationToTicks24MHz(deadline.time_since_epoch())before sampling the hardware counter and delegate directly toPreciseSleepUntilTicks24MHz:steady_clock::now()runtime calls on the 24 MHz path: WhenPreciseQpcFrequency() == 24000000ULL, the new branch bypassessteady_clock::now()(which on Windows MinGW-w64libstdc++invokeslibwinpthread!clock_gettime(CLOCK_MONOTONIC)on every call).PreciseSleepUntilTicks24MHz, the spin-loop pollsQueryPerformanceCounterdirectly and compares againsttargetTickswith a single 64-bit integer comparison (cmp), with zero frequency queries (once cached) and zero runtime divisions in the polling loop. Delays exceeding 6000 ticks (250 µs) sleep via waitable timer withPreciseTicksToHundredNanos24MHz. (Note: the fallback path for other frequencies continues to usesteady_clock::now()).PreciseDurationToTicks24MHzsupports standard durations (nanoseconds,microseconds,milliseconds,seconds). Coarse durations scale without division and saturate safely toUINT64_MAXinstead of overflowingint64_t. Fractional and arbitrary ratio periods (e.g.NearSecondDuration{INT64_MAX - 1}) are handled byPreciseFractionalProductDivbit-by-bit without 64-bit intermediate overflow.core/libs/tests/PreciseWait.cppunder#ifdef _WIN32for compile-time constants (PreciseTicksToHundredNanos24MHz(UINT64_MAX) == 7686143364045646506ULL), duration conversion & saturation across standard durations and large denominators (NearSecondDuration{INT64_MAX - 1}), as well as runtime coverage ofPreciseSleepUntilTicks24MHz(early return, spin-loop polling, and hybrid waitable timer paths).objdump -d -M intel(Windows x64PreciseSleepUntilProduction24 MHz fast-path)PreciseSleepUntilProduction(disassembly of 24 MHz branch fromdisasm_24mhz_pr6620.o):Complete source for the synthetic microbenchmark
The following standalone harness produced the measurements below. It requires a Windows host with a 10 MHz QPC and maps host QPC ticks to synthetic 24 MHz ticks. It does not measure physical 24 MHz hardware.
Build from the repository root with MinGW-w64 GCC 15.2.0:
Tested
x86_64, Zen 4, 5.20 GHz)-std=c++20 -O3)core/libs/tests/PreciseWait.cpprebased on latestmain(Passed).python tools/check_conventions.py --base origin/main(All conventions checks passed).python tools/pr_overlap.py --branch perf/windows-24mhz-qpc-fastpath(automatic check required manual review; manual review confirms PR 6044 touches CTest organization and PR 7332 touches only__APPLE__branches, with no functional overlap).git diff --check(Passed).Test Scope & Performance Note
core/libs/tests/PreciseWait.cppruns under#ifdef _WIN32and exercisesPreciseSleepUntilTicks24MHzdirectly (verifying early return, spin-loop polling completion, and waitable timer execution). On standard 10 MHz CI hosts, top-levelPreciseSleepUntildispatches to the 10 MHz branch.AGENTS.mdwould requiretools/trace_digest.pysummaries ofmainand the change from the same machine and scene with attached traces).scratch/bench_24mhz.cpp(50,000 samples, pinned to Core 0, High Priority) on a 10 MHz host, where candidate includes additional cost of 10-to-24 MHz tick mapping; this is not a measurement of physical 24 MHz hardware. Mean and tail percentiles vary slightly between runs due to OS thread scheduling jitter; the recorded run below reflects a fixed captured execution.Isolated Primitive Microbenchmark Run (
bench_24mhz.cpp)main(post-#6620 Fallback)steady_clock::time_point[ns])MinGW GCC 15.2)p50: 416 cyc (80.0 ns)p90: 468 cycmean: 444.9 cycmin: 416 cycp50: 208 cyc (40.0 ns)p90: 208 cycmean: 204.3 cycmin: 156 cyccmpvs 1 QPC + 2×steady_clock::now()(candidate includes 10→24 MHz synthetic mapping)MinGW GCC 15.2)p50: 208 cyc (40.0 ns)p90: 260 cycmean: 246.4 cycmin: 208 cycp50: 208 cyc (40.0 ns)p90: 208 cycmean: 209.9 cycmin: 156 cycQueryPerformanceCounterpolling vssteady_clock::now()(candidate includes synthetic mapping overhead)Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file.mdfiles or images added to the repository (attach them to this PR)Imported from boykopovar/AnyPS5. Originally posted by github-actions[bot] on 2026-10-19T21:26:57Z.
This pull request is labeled
perf, so it needs the summary line of a capture onmainand one with the change, from the same title, scene and machine, as the Performance report form asks. Please paste bothaps5-summary.jsonllines, attach the two traces and add the output oftools/trace_digest.py.Imported from boykopovar/AnyPS5. Originally posted by xXPBSXx on 2026-10-20T05:06:09Z.
Windows data point for
6fb9d2c0amerged ontomainb50976750(clean,git merge-treerc 0): Windows 10.0.19045, MinGW-w64 GCC 15.2.0, Release (CMAKE_BUILD_TYPE:STRING=Releasein the build'sCMakeCache.txt).ctest -N -R '^precise_wait$'lists exactly that one test;ctest --no-tests=error -R '^precise_wait$'was run three times per tree.core/libs/prx/libc/include/PreciseWait.hpprestored tomain(the new test kept):precise_wait_testsdoes not compile (PreciseTicksToHundredNanos24MHz,PreciseDurationToTicks24MHzandPreciseSleepUntilTicks24MHzare not declared), so there is nothing to run without the change.The QPC frequency of this machine is 10 MHz (
Stopwatch.Frequency= 10000000), so the newPreciseQpcFrequency() == 24000000ULLbranch ofPreciseSleepUntilis not taken here; only the 24 MHz helpers the test calls directly are exercised. This is not a performance measurement and does not supply the numbers theperf numbers missinglabel asks for. Not tested: a host whose QPC runs at 24 MHz, other platforms, a title run.AI-assisted (Claude Code).
Imported from boykopovar/AnyPS5. Originally posted by hamb3r on 2026-10-20T08:43:32Z.
Thanks for the verification run @xXPBSXx!
As noted in the PR description, since 10 MHz hosts (including our Ryzen 7 7700 machine) take the #6620 branch in
PreciseSleepUntil, the 24 MHz path was verified via the synthetic primitive benchmark (416 cyc -> 208 cyc,2.00xon expired calls) andobjdump -dr -M inteldisassembly comparison (MinGW-w64 GCC 15.2.0 -O3) between the Before (mainfallback path on 24 MHz) and After (24 MHz fast path) codegen:mainfallback path at0xfd..0x1d9): Even whendeadlinehas already passed, the fallback path executes 3 external calls (__imp_QueryPerformanceCounterat0x109, followed by two calls to_ZNSt6chrono3_V212steady_clock3nowEvat0x10band0x1b0, each invokinglibwinpthread!clock_gettime->QueryPerformanceFrequency+QueryPerformanceCounter+ nanosecond scaling), and calls_ZNSt6chrono3_V212steady_clock3nowEvon every spin-loop poll (0x1b0..0x1d7).0x1ea..0x2a3): Scalesdeadlineonce in registers via branchless reciprocal multiplication (movabs rcx, 0x20c49ba5e353f7cf/imul rcx, zerodivinstructions), makes 1QueryPerformanceCountercall (0x251: call rsi) +cmp rax, rbx(0x25d) for an immediate return on expired deadlines (eliminating bothsteady_clock::now()calls), and pollsQueryPerformanceCounterdirectly in the spin loop (0x280..0x2a3).Before vs After
objdump -dr -M intel(MinGW-w64 GCC 15.2.0 -O3)Imported from boykopovar/AnyPS5. Originally posted by wachi35676 on 2026-10-20T11:29:47Z.
I ran
PreciseSleepUntilitself on a simulated 24 MHz QPC, which goes further than the directPreciseSleepUntilTicks24MHzcalls in the unit test. Windows 11 (10.0.26300), Ryzen 5 9600X (host QPC 10 MHz), WinLibs GCC 15.2.0,-O2. Head6fb9d2c0amerged ontomain02fb1ce53.precise_wait: passes 3 of 3. WithPreciseWait.hppreverted tomainthe test does not compile, as @xXPBSXx reported.PreciseWait.hppfrommainor from this PR, withQueryPerformanceFrequency/QueryPerformanceCounterredirected to a counter that reports frequency F and returnshostQpc * F / 10 MHz.steady_clock(winpthreads, real QPC) stays on the same timeline, so F = 24 MHz takes the new branch with the deadline conversion and the 6000-tick spin tail, and F = 19.2 MHz takes the generic path. For each target T it callsPreciseSleepUntil(steady_clock::now() + T)and measuressteady_clock::now() - deadline: 2000 calls per target, 200 for 4 ms and 16.667 ms. It ran atHIGH_PRIORITY_CLASSwhile other builds held the CPU at 100%.main(generic path)On this loaded machine the two distributions overlap, and the difference between them is within run-to-run noise. A first run at normal priority gave p50 values of 5 to 26 ms at 300 µs and above for both versions. Both versions also wake about 200 µs late at 300 µs, which comes from the timer's resolution, not from this change.
mainwithin noise, and there are no early returns.steady_clockdeadline. I found no accuracy gain or loss on this host. The per-call saving the description reports (about 200 cycles on an expired deadline) is far below the timer's wake-up jitter here.AI-assisted: yes (Claude Code); results above were run on this machine.
Imported from boykopovar/AnyPS5. Originally posted by hamb3r on 2026-10-20T11:40:33Z.
Thanks @wachi35676 for running the simulated 24 MHz and 19.2 MHz QPC tests and verifying both the fast path and the fallback path!
Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-20T20:32:38Z.
Review: CHANGES_REQUESTED
Thanks for the work and for the thorough synthetic checks. Two things are needed before this can merge:
perfand has noaps5-summary.jsonllines nortools/trace_digest.pyoutput formainvs this change on the same machine and scene (AGENTS.md, "A speed claim"). The microbenchmark maps a 10 MHz QPC to a virtual 24 MHz and measures ~40 ns per call, so it is not a measurement of the affected path.QueryPerformanceFrequency() == 24000000with this x86-64 build, and ideally attach a capture from it. Without such a host the new branch (~100 lines including the bitwisePreciseFractionalProductDivfor arbitrary ratios) is never executed by CI or by the hosts tested so far (10 MHz), and the saving per sleep call is tens of nanoseconds. If no such host exists, please close this; if one does, consider dropping the generic-ratio fallback, sincesteady_clockis always nanoseconds here.The conversion math and the static_asserts look correct, and thanks to @xXPBSXx and @wachi35676 for the Windows runs.
Imported from boykopovar/AnyPS5. Originally posted by hamb3r on 2026-10-20T20:46:17Z.
Thanks for the review @adriadam10!
To answer your questions transparently:
Where
QueryPerformanceFrequency() == 24000000occurs on Windows:CNTFRQ_EL0 = 24,000,000 Hz) is exposed directly asQueryPerformanceFrequency().CPUID.15H) when the platform clock is forced (bcdedit /set useplatformclock true) or on pre-1809 builds before Windows began normalizing invariant TSC to10,000,000 Hzin user mode (which is why modern x86-64 Windows 10/11 on both AMD and Intel — including @xXPBSXx's i5-13400F — report 10 MHz and already hit the #6620 fast path).aps5-summary.jsonl/tools/trace_digest.pyfrom.How the optimization was verified:
objdump -dr -M inteldisassembly inspection (verifying the elimination ofsteady_clock::now()/clock_gettimecalls anddivinstructions) and synthetic microbenchmarks (plus @wachi35676's simulated 24 MHz QPC harness).How would you prefer to proceed?
I'd be happy to go with whichever option you prefer as a collaborator:
PreciseFractionalProductDiv(~45 lines of bitwise division for non-standarddurationratios) and keep only the compactsteady_clocknanosecond conversion ((ns * 3 + 124) / 125), reducing the entire change from ~100 lines to ~30 lines; oraps5-summary.jsonlcapture from a 24 MHz host.Pull request closed