perf(libc): add steady_clock fast path in PreciseSleepUntil #6620
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/6620"
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-15T23:14:54Z.
What
PreciseQpcFrequency()soPreciseSleepFromCounterWithTimerandPreciseSleepUntilshare the cachedQueryPerformanceFrequencyvalue on Windows.std::chrono::steady_clockfast path inPreciseSleepUntilon both Windows (PreciseQpcFrequency() == 10000000ULL,10 MHzQPC) and POSIX/Linux (PreciseMonotonicNanos()) that convertsdeadline.time_since_epoch()to hardware clock ticks before sampling the hardware clock and delegates directly toPreciseSleepFromCounter/PreciseSleepFromNanos:steady_clock::now()reads per call: On currentmain,PreciseSleepUntilreads the hardware clock (QueryPerformanceCounteron Windows,PreciseMonotonicNanoson POSIX), then immediately callsTClock::now()(which on Windows MinGW-w64libstdc++callslibwinpthread!clock_gettime(CLOCK_MONOTONIC)-> uncachedQueryPerformanceFrequency+QueryPerformanceCounter+ three 64-bitidivinstructions, and on Linux callssteady_clock::now()@PLT), and then callsTClock::now()a third time in the post-wait epilogue loop — performing 3 hardware clock reads even when the deadline has already expired.T_0vsT_1sampling skew: Onmain, the initial hardware counter is sampled atT_0andnow = TClock::now()is sampled atT_1 > T_0. Computingremaining = deadline - now(deadline - T_1) and adding it to the counter sampled atT_0causesPreciseSleepFromCounter/PreciseSleepFromNanosto wake up atT_0 + (deadline - T_1) = deadline - (T_1 - T_0), systematically undershootingdeadlineand forcing execution into thefor (auto current = TClock::now(); ...)epilogue loop.* 100and 128-bit/ 100division afterQueryPerformanceCounteron Windows (10 MHz): By the integer identity checkingif (rawDeadline <= 0) [[unlikely]] { return; }and precomputingtargetHnsbeforeQueryPerformanceCounter(&counter)removesimul(* 100), 128-bitmul 0x28f5c28f5c28f5c3(/ 100), andaddfrom the timing-critical window after sampling the counter, leaving a singlesubinstruction (targetHns - nowTicks). For coarsertime_pointdurations (such asmicroseconds), division is eliminated completely (add + leafor* 10).PreciseMonotonicNanos()on Applelibc++(__APPLE__ && _LIBCPP_VERSION && CLOCK_MONOTONIC_RAW) to useclock_gettime(CLOCK_MONOTONIC_RAW, &ts)so it shares the exact clock source and sub-microsecond resolution oflibc++'sstd::chrono::steady_clock::now()(which also fixesPreciseSleepUsreturning up to1 usearly againststeady_clockon macOS due toCLOCK_MONOTONIC's1000 nsresolution), and gate the non-Windowssteady_clockfast path to configurations with guaranteed matching clock sources.core/libs/tests/PreciseWait.cppfor zero-epoch (steady_clock::time_point{}) and coarse-duration (time_point<steady_clock, microseconds>) deadlines.llvm-objdump -d --x86-asm-syntax=intel(Windows x64PreciseSleepUntil<steady_clock>: Before vs After)Before (
main: callsQueryPerformanceCounter, then callssteady_clock::now(), performs 128-bit/ 100division after QPC, and loops onsteady_clock::now()again at exit):After (
PR: 0 calls tosteady_clock::now();targetHnsprecomputed beforeQueryPerformanceCounter; onlymov + sub + jbeafterQueryPerformanceCounter):After (for
time_point<steady_clock, microseconds>: 0 divisions anywhere in the function):objdump -d -M intel(Linux x86_64PreciseSleepUntil<steady_clock>: Before vs After)Before (
main: callsclock_gettime, then immediately callssteady_clock::now()@PLT, and callssteady_clock::now()@PLTagain in the epilogue loop):After (
PR: 0 calls tosteady_clock::now()@PLT; singleclock_gettimecall):Tested
x86_64, Zen 4)x86_64, MinGW-w64 GCC 15.2): Builtprecise_wait_tests,libkernel,libSceAudio3d,libSceAudioInand ranctest --test-dir build -R precise_wait --output-on-failure(Passed, 0.13 sec).x86_64, Dockeranyps5-env:archGCC 16.2.1 &anyps5-env:ubuntuGCC 11.4.0): Compiled and rancore/libs/tests/PreciseWait.cpp(Passed).Apple M2 Max,arm64native &x86_64Rosetta, Apple Clang 21.0.0libc++): VerifiedPreciseSleepUntil(now + 1ms)(1.10–1.17 msvs1.15–1.23 msonmain) and 20/20 runs ofcore/libs/tests/PreciseWait.cpp(0/20failures vs20/20early-return failures onmain).python3 tools/check_conventions.py --base origin/main(All conventions checks passed).1. CPU Cycle Benchmark (
__rdtscpon AMD Ryzen 7 7700, Before vs After on the same machine, pinned to core 0)main(post-#5827)#10 + #15+ Linux fast-path)PreciseSleepUntil(past)(steady_clock::time_point[ns])MinGW-w64 GCC)p50: 416 cycp90: 416 cycmean: 447.6 cyc (115.3 ns)p50: 156 cycp90: 156 cycmean: 154.8 cyc (59.1 ns)−62.5%, 2.67× faster)idivinlibwinpthread)PreciseSleepUntil(past)(steady_clock::time_point[ns])ArchLinux GCC 16.2)p50: 364 cycp90: 364 cycmean: 351.9 cyc (100.4 ns)p50: 156 cycp90: 156 cycmean: 165.0 cyc (61.5 ns)−57.1%, 2.33× faster)clock_gettimeinstead of 3clock_gettimePreciseSleepUntil(past)(steady_clock::time_point[ns])Ubuntu GCC 11.4)p50: 364 cycp90: 364 cycmean: 349.8 cyc (98.1 ns)p50: 156 cycp90: 208 cycmean: 180.6 cyc (64.5 ns)−57.1%, 2.33× faster)clock_gettimeinstead of 3clock_gettimePreciseSleepUntil(past)(time_point<steady_clock, us>)MinGW-w64 GCC)p50: 416 cycp90: 416 cycmean: 409.7 cyc (108.0 ns)p50: 156 cycp90: 156 cycmean: 154.6 cyc (72.7 ns)−62.5%, 2.67× faster)* 10viaadd + lea)PreciseSleepUntil(past)(time_point<steady_clock, us>)ArchLinux/Ubuntu)p50: 364 cycp90: 364 cycp50: 156 cycp90: 156–208 cyc−57.1%, 2.33× faster)clock_gettimeinstead of 3clock_gettimePreciseSleepUntil(epoch <= 0)(steady_clock::time_point{})p50: 364–416 cycmean: 349–427 cycp50: 52 cycmean: 67.9–69.4 cyc−85.7%..−87.5%)rawDeadline <= 0)QPC(steady_clock[ns])x86_64)p50: 11.02 cycp90: 11.13 cycp50: 4.89 cycp90: 4.99 cyc−55.6%)subafter QPC instead ofimul 100+ 128-bitmul+shr+addtime_point<steady_clock, us>)x86_64)p50: 14.04 cycp90: 14.14 cycp50: 5.10 cycp90: 5.10 cyc−63.7%)/ 100division eliminated completely2. Per-Call Latency, Total Cycles & Wakeup Overshoot (
mainafter #5827 vs PR)main(avg / p50 / p90 / p99 / p50 cycles / overshoot)PreciseSleepUntil(+500 ns)MinGW-w64)0.50 us/0.50 us/0.50 us/0.50 us/2704 cyc0.50 us/0.50 us/0.50 us/0.50 us/2600 cyc(−104 cyc exit overhead)PreciseSleepUntil(+1 us)MinGW-w64)1.00 us/1.00 us/1.00 us/1.00 us/5356 cyc1.00 us/1.00 us/1.00 us/1.00 us/5200 cyc(−156 cyc exit overhead)PreciseSleepUntil(+50 us)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)Ubuntu)51.33 us/50.10 us/56.30 us/98.70 us/ overshoot p50101 ns(mean1331 ns)50.98 us/50.00 us/55.40 us/76.10 us/ overshoot p502 ns(mean982 ns, −26.2%)PreciseSleepUntil(+1000 us)MinGW-w64)1046.36 us/1018.20 us/1103.60 us/2120.90 us/ overshoot mean46.36 us1024.52 us/1000.00 us/1117.40 us/1439.90 us/ overshoot mean24.52 us(−47.1%)PreciseSleepUntil(+1000 us)ArchLinux)1006.40 us/1006.74 us/1012.24 us/1038.24 us/ overshoot p506736 ns(mean6399 ns)1003.96 us/1002.24 us/1009.54 us/1064.44 us/ overshoot p502236 ns(mean3960 ns, −38.1%)PreciseSleepUntil(+1000 us)Ubuntu)1006.52 us/1005.83 us/1011.33 us/1059.43 us/ overshoot p505832 ns(mean6525 ns)1004.46 us/1003.43 us/1010.53 us/1027.93 us/ overshoot p503432 ns(mean4462 ns, −31.6%)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 hamb3r on 2026-10-15T23:15:04Z.
cc @adriadam10 @CnRJay — follow-up to #5827, would appreciate your review when you have a moment!
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()andCLOCK_MONOTONICshare the same epoch/rate, then compares their absolute nanosecond values. On macOS, libc++ implementssteady_clockwithCLOCK_MONOTONIC_RAW(seellvm-project/libcxx/src/chrono.cpp,__libcpp_steady_clock_now), while this helper callsclock_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 fromTClock::now()on platforms where the clock source is not guaranteed to match, or use a platform clock source that is explicitly the same assteady_clock? The finalTClock::now()loop prevents an early return but does not correct an oversized sleep.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.
core/libs/tests/PreciseWait.cppcore/libs/prx/libc/include/PreciseWait.hppImported 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 acrosslibc++(libcxx/src/chrono.cpp) andlibstdc++(libstdc++-v3/src/c++11/chrono.cc):libc++,libcxx/src/chrono.cpp): WhereasPreciseMonotonicNanos()incore/libs/prx/libc/include/PreciseWait.hppwas unconditionally calling:libstdc++-v3/src/c++11/chrono.ccandlibcxx/src/chrono.cppunder_LIBCPP_HAS_CLOCK_GETTIME):Both
libstdc++andlibc++callclock_gettime(CLOCK_MONOTONIC, &tp)and constructseconds(tp.tv_sec) + nanoseconds(tp.tv_nsec), matchingPreciseMonotonicNanos().Addressed in
a7b8a697d(core/libs/prx/libc/include/PreciseWait.hpp):PreciseMonotonicNanos(), useclock_gettime(CLOCK_MONOTONIC_RAW, &ts)whendefined(__APPLE__) && defined(_LIBCPP_VERSION) && defined(CLOCK_MONOTONIC_RAW)so it uses the exact same clock source aslibc++'sstd::chrono::steady_clock::now()on macOS (while keepingCLOCK_MONOTONICon Linux wherePreciseSleepFromNanosWithSlackusesclock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, ...)).PreciseSleepUntil(), guard the non-Windowssteady_clockfast path with: so any platform or standard library configuration where the clock source is not explicitly guaranteed to match keeps theTClock::now()remaining-duration calculation.std::chrono::steady_clock::now()SourcePreciseWaitHardware Clock Source (Beforea7b8a697d)PreciseWaitHardware Clock Source (Aftera7b8a697d)PreciseSleepUntil<steady_clock>Path_WIN32,10 MHzQPC)QueryPerformanceCounterQueryPerformanceCounterQueryPerformanceCounter(unchanged)targetHns - nowTicksfast path__linux__,libstdc++/libc++)CLOCK_MONOTONICCLOCK_MONOTONICCLOCK_MONOTONIC(unchanged)targetNanos - startNanosfast path__APPLE__,libc++)CLOCK_MONOTONIC_RAWCLOCK_MONOTONIC(mismatched)CLOCK_MONOTONIC_RAW(aligned)targetNanos - startNanosfast pathCLOCK_MONOTONICCLOCK_MONOTONICdeadline - TClock::now()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.
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, basemainaff725bf6. Fullmaindoes not build on macOS, so I compiledPreciseWait.hppstandalone:core/libs/tests/PreciseWait.cppplus a small repro that callsPreciseSleepUntil(steady_clock::now() + 1ms).Clock sources on this machine.
steady_clock::now()matchesCLOCK_MONOTONIC_RAWto well under 1 µs.CLOCK_MONOTONICruns 2208 ms behind it, andclock_getresreports 1000 ns for it, against 42 ns (arm64) and 1 ns (x86_64) for RAW. The new__APPLE__ && _LIBCPP_VERSION && CLOCK_MONOTONIC_RAWgate evaluates true on both architectures.Repro,
PreciseSleepUntil(now + 1ms), 3 calls per build, arm64 and x86_64 the same:mainaff725bf678ce0b836a7b8a697dSo the clock mismatch @MarcZX100 described was real on macOS: the absolute-deadline fast path overslept by the full
CLOCK_MONOTONICvs RAW offset, here about 2.2 s per call.a7b8a697dfixes it.core/libs/tests/PreciseWait.cpp, 20 runs per build withAPS5_SKIP_TIMING_TESTS=1(this skips the median bounds and keeps the "returned before its requested duration" checks):mainaff725bf6a7b8a697dOn
mainthe failures arePreciseSleepUs returned before its requested durationandPreciseSleepUs(50) returned before its requested duration.PreciseMonotonicNanos()there readsCLOCK_MONOTONIC, which has 1 µs resolution on macOS, while the test measures withsteady_clock(RAW). MovingPreciseMonotonicNanos()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.
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 (
arm64native andx86_64Rosetta) and verifying both thePreciseSleepUntil(now + 1ms)timings and thePreciseWait.cppCLOCK_MONOTONIC_RAWresolution fix! Updated the PR description (WhatandTestedsections) to document this.Imported from boykopovar/AnyPS5. Originally posted by simonbronk on 2026-10-16T13:39:35Z.
Independent Windows CPU check of head
a7b8a697de5b8c67a6e8736f30f98fb4513631d7against current main82ddae75b6761757f3d3ba9c0723647469270f76(AI-assisted, OpenAI Codex).Compiled both unchanged
PreciseWait.hpp/HostThreadLocal.hpppairs, each ref's unchangedPreciseWait.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_TESTSis 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:
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 withg++ -std=c++20 -O3 -DNDEBUG -static -pthread -I<variant> probe.cpp -o probe.exe, and compile that variant's originalPreciseWait.cppwith 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)
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;mainaf0fff762vsmain+ 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).maina7b8a697d)Within the run-to-run spread (
mainitself moved 6.61 -> 6.76 between rounds), no regression, 0 fatal.AI-assisted: yes (Claude Code)
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!
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
a7b8a697donmain47a266cf9with my macOS series (the libraries do not link on macOS without it).CLOCK_MONOTONICcounts whole microseconds on macOS (clock_getresreports 1000 ns,CLOCK_MONOTONIC_RAW1 ns), so onmainprecise_waitfails withPreciseSleepUs(50) returned before its requested duration. With this pull request it passes those checks.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 thenanosleepbefore the spin about a quarter of its length late for a thread without a time-constraint policy. In a standalone program a 1.4 msnanosleepreturned 360 µs late, and so didmach_wait_untiland a thread with the user-interactive QoS class, as x86-64 and as arm64. UnderTHREAD_TIME_CONSTRAINT_POLICYit 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.