perf(libc): add sub-tick spin tail to PreciseSleepUs and PreciseSleepUntil #5827
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/5827"
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-14T12:42:07Z.
What
_WIN32): Replaces the full-durationSetWaitableTimer+WaitForSingleObjectsleep inPreciseSleepHundredNanosand the repeatedPreciseSleepUsloop inPreciseSleepUntilwithPreciseSleepFromCounterWithTimer.PreciseSleepUntil) and long pacing sleeps (PreciseSleepUs>= 1000 us): Sleep on the thread-local high-resolution waitable timer forduration - 250 us(with a safe fallback tostd::this_thread::sleep_forif the timer handle is invalid orSetWaitableTimer/WaitForSingleObjectfails) and finish the remaining250 ussub-tick window usingQueryPerformanceCounter+YieldProcessor()(gated to remaining time> 200 ns).PreciseSleepUs< 1000 us): Sleep for the full requested duration on the thread-local high-resolution waitable timer without subtracting a spin tail (allowSpinTail = false), so poll loops (Pm4.cppWAIT_REG_MEM,Apr.cppWAIT_MEM,Aio.cpp,AudioOut2Context.cpp,Font/State.cpp) block in the kernel timer rather than busy-spinning a core on Windows (0.84%of a core in a tightPreciseSleepUs(50)x500loop).10 MHzQPC frequencies use ceiling conversion (PreciseHundredNanosToQpcTicks) and frequency-scaled pause thresholds (PrecisePauseThresholdTicks) so sleeps never return early on3.58 MHz/14.32 MHz/24 MHzcounters.!_WIN32 && !__EMSCRIPTEN__): Replaces the repeatednanosleeploop inPreciseSleepUsandPreciseSleepUntilwithPreciseSleepFromNanosusingclock_gettime(CLOCK_MONOTONIC). On Linux (__linux__), cachesprctl(PR_SET_TIMERSLACK, 1UL, ...)once per thread (thread_localinPreciseLinuxLowTimerSlack()) and sleeps viaclock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME)up to a15 usspin tail (100 usconservative fallback ifPR_SET_TIMERSLACKis denied byseccomp, and100 usnanosleeptail on non-Linux POSIX), finishing the final window with_mm_pause()on x86 (std::atomic_signal_fenceon non-x86) gated to remaining time> 200 ns.10-200 us):Aio.cpp(10 us),Font/State.cpp(30 us),Pm4.cpp(50 usWAIT_REG_MEM),Apr.cpp(50 usWAIT_MEM), andAudioOut2Context.cpp(200 usFULL_WAIT_STEP). On Linuxmain,10-50 ussleeps take75-118 usdue to the default50 ustimer slack + scheduler latency; with the15 ustail on Linux,50 ussleeps still block inclock_nanosleepfor35 usand use7.99 usCPU/call (vs7.38 usonmain,1.08x). On Windows, shortPreciseSleepUs(< 1000 us) remain pure waitable-timer sleeps (~4.05 usCPU/call,0.84%core in a tight50 uspoll loop).1000-16667 us) &PreciseSleepUntildeadlines:AudioIn(1000 us),AudioOut/Audio3d(5333 us,187.5 Hz),VideoOutDriver(8341-16667 us), andPreciseSleepUntilcallers, where eliminating the per-frame timer overshoot keeps pacing on-target at0.23%of one core on Linux (vs0.26%onmain) and1.00%of one core on Windows (53.4 usCPU/frame at187.5 Hz).Tested
Linux Per-Call Latency & CPU Cost (
x86_64,CLOCK_MONOTONIC+CLOCK_THREAD_CPUTIME_ID, 300 iterations)main(avg / p50 / p99)mainCPU/callPreciseSleepUs(10)(Aio)78.19 us/74.61 us/116.01 us7.21 us10.23 us/10.00 us/19.90 us10.24 us1.42xPreciseSleepUs(50)(Pm4/Apr)117.95 us/117.11 us/130.31 us7.38 us52.71 us/50.10 us/62.81 us7.99 us1.08xPreciseSleepUs(100)(usleep)169.36 us/170.31 us/196.22 us7.75 us104.35 us/104.31 us/124.31 us8.40 us1.08xPreciseSleepUs(1000)(AudioIn)1071.21 us/1071.49 us/1089.79 us8.61 us1005.17 us/1003.99 us/1020.79 us8.47 us0.98xPreciseSleepUs(5333)(AudioOut)5421.69 us/5408.46 us/5475.36 us11.81 us5346.72 us/5344.85 us/5382.66 us13.64 us1.15xWindows Per-Call Latency & CPU Cost (
x86_64,QueryPerformanceCounter+QueryThreadCycleTime)main(avg / p50 / p99)mainCPU/callPreciseSleepUs(50)(Pm4/Apr)552.07 us/516.90 us/1011.40 us3.86 us523.92 us/516.50 us/1008.40 us4.05 us< 1000 us)PreciseSleepUs(100)(usleep)564.98 us/515.80 us/1019.30 us3.63 us519.04 us/515.30 us/594.50 us4.08 us< 1000 us)PreciseSleepUs(200)(AudioOut2)544.06 us/516.40 us/1041.10 us4.00 us518.47 us/514.70 us/578.40 us3.95 us< 1000 us)PreciseSleepUs(1000)(AudioIn)1550.13 us/1523.00 us/2055.90 us3.40 us1018.00 us/1000.20 us/1438.60 us24.59-63.15 us250 ustail)PreciseSleepUntil(+50 us)552.07 us/516.90 us/1011.40 us3.86 us51.10 us/50.00 us/97.70 us49.10 us250 ustail)Representative High-Frequency Callers (Total Wall Time & Total CPU Usage)
main(Wall / Frame p50 / Total CPU /% Core)% Core)AudioOut187.5 Hzpacing (200frames x5333.3 us=1066.7 ms)1066.75 ms/5333.15 us/2.81 ms(0.26%core)1066.68 ms/5332.77 us/2.45 ms(0.23%core)AudioOut187.5 Hzpacing (200frames x5333.3 us=1066.7 ms)1066.94 ms/5373.60 us/0.93 ms(0.09%core)1066.84 ms/5333.00 us/10.69 ms(1.00%core)PreciseSleepUs(50)x500calls59.32 ms(118.6 us/iter) /3.65 ms(7.31 us/call,6.16%core)25.71 ms(51.4 us/iter) /4.02 ms(8.04 us/call,15.64%core)PreciseSleepUs(50)x500calls256.80 ms(513.6 us/iter) /1.93 ms(3.86 us/call,0.75%core)251.62 ms(503.2 us/iter) /2.11 ms(4.22 us/call,0.84%core)Unit & CTest Verification
core/libs/tests/PreciseWait.cppto use a 65-sample median (CheckMedianSleepBound, up to 3 windows) with a busy-runner preemption guard (IsRunnerPreempted+APS5_SKIP_TIMING_TESTSopt-out) so loaded CI runners do not flake:PreciseSleepUntil(+50 us)< 90 usmedian on all platforms andPreciseSleepUs(50)< 90 usmedian on non-Windows.PreciseSleepUs(1500), ceiling QPC tick conversion (PreciseHundredNanosToQpcTicks) across3.58-24 MHz, sub-microsecond and millisecond deadlines, invalid waitable timer handle fallback on Windows, and conservative100 ustail fallback on Linux.-Wall -Wextra -Werror).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-14T12:53:56Z.
сс @adriadam10 @oneandonlydean
Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-14T13:54:32Z.
Review: CHANGES_REQUESTED
Thanks for the measurements; I reproduced the latency gain on Linux (main vs PR, 300 iterations):
PreciseSleepUs(10)74.8 → 15.0 µs,(100)163 → 111 µs,(1000)1081 → 1007 µs. Build and ctest are green. Points to address:CLOCK_THREAD_CPUTIME_IDper call goes from ~8 µs to ~50 µs for sleeps of 50 µs-1 ms (6x), because every such sleep now ends in a ~50 µs busy spin (550 µs on Windows). Please measure a representative high-frequency caller (a thread loopingsceKernelUsleep(50), or AudioOut pacing) before/after in total CPU use, and say which callers justify spinning.core/libs/tests/PreciseWait.cpp:27-49only asserts that a sleep never returns early, whichmainalready satisfies; it passes without the change. Add an assertion that fails onmain, e.g. a median over N iterations ofPreciseSleepUs(50)staying within a bound of the target thatmainexceeds on Linux (use a generous bound and the median so it is not flaky on loaded CI).PreciseWait.hpp,PreciseSleepOsNanosWithSlack): two to three extraprctlsyscalls per sleep on the hot path. Cache the thread's slack once (thread_local) instead of get/set/restore each call, or justify the cost with a measurement.precise_waitonce dispatched.Happy to re-review once these are addressed.
Imported from boykopovar/AnyPS5. Originally posted by hamb3r on 2026-10-14T14:59:50Z.
@adriadam10 Thanks for the review! Addressed all three points:
PR_SET_TIMERSLACKonce per thread (thread_local):PreciseLinuxLowTimerSlack()now runsprctlonce per thread (0prctlsyscalls on the hot path) while still falling back to the100 ustail ifprctlfails.15 uson Linux,250 uson Windows) & measured CPU cost:1 nstimer slack on Linux, kernel wake-up latency is~15 us, so shrinking the Linux spin tail from50 usto15 usallows50 ussleeps to block inclock_nanosleepfor35 us. Per-callCLOCK_THREAD_CPUTIME_IDfor50 us - 1 msdrops back to~8.0-8.5 us/call(1.08xvsmain's7.4-8.6 us/call).kSpinTailHundredNanosfrom550 usto250 usstill covers all sub-tick polling callers (Aio10 us,Font30 us,Pm4/Apr50 us,AudioOut2200 us) while cutting CPU cost on1000 us(AudioIn) from429 usto24.6 us/calland onAudioOut(187.5 Hz) from4.02%to1.00%of one core.main(Wall / p50 / CPU)PreciseSleepUs(50)(Pm4/Apr)117.95 usavg /117.11 usp50 /7.38 usCPU52.71 usavg /50.10 usp50 /7.99 usCPU (1.08x)PreciseSleepUs(100)(usleep)169.36 usavg /170.31 usp50 /7.75 usCPU104.35 usavg /104.31 usp50 /8.40 usCPU (1.08x)PreciseSleepUs(1000)(AudioIn)1071.21 usavg /1071.49 usp50 /8.61 usCPU1005.17 usavg /1003.99 usp50 /8.47 usCPU (0.98x)AudioOut187.5 Hz(200frames,1066.7 ms)1066.75 ms/5333.15 usp50 /2.81 msCPU (0.26%core)1066.68 ms/5332.77 usp50 /2.45 msCPU (0.23%core)AudioOut187.5 Hz(200frames,1066.7 ms)1066.94 ms/5373.60 usp50 /0.93 msCPU (0.09%core)1066.84 ms/5333.00 usp50 /10.69 msCPU (1.00%core)PreciseSleepUs(50)x500(25.0 mstarget)59.32 mswall (118.6 us/iter) /3.65 msCPU (7.31 us/call)25.71 mswall (51.4 us/iter) /4.02 msCPU (8.04 us/call)core/libs/tests/PreciseWait.cpp: asserts that the median of 31PreciseSleepUs(50)calls is< 90 us(fails onmainat117.5 uson Linux and518.0 uson Windows; passes at~50.1 uswith this PR).Imported from boykopovar/AnyPS5. Originally posted by CnRJay on 2026-10-14T19:16:49Z.
Review: COMMENTED
The Linux half now looks right: 1 ns slack, a 15 µs tail and about 8 µs of CPU per call.
The Windows half has a cost the per-call tables don't show. With a 250 µs tail, any
PreciseSleepUsof 250 µs or less never reaches the waitable timer, so it is a pure busy-wait. The Windows table confirms it: 49 µs of CPU for a 50 µs sleep, and 200 µs for 200 µs. Those calls are not one-shot sleeps, though. They are poll loops that repeat until something else happens, so on Windows the CPU cost is the whole wait, not the sleep length:Pm4.cpp:1006,WAIT_REG_MEM/0x93: the queue thread polls a value written "by the CPU or another queue". A wait on a guest CPU write can last a large part of a frame. Onmainthat is about two wakeups per millisecond; with this change the thread spins for the entire wait.Apr.cpp:655(WAIT_MEM),Aio.cpp:276/301(completion polls),AudioOut2Context.cpp:341(FULL_WAIT_STEPloop),Font/State.cpp:60: the same shape.Each of these loops now holds a core for as long as it waits. This emulator is usually CPU-bound: queue 0 at 95–99 %, eight shader-prepare threads at about 90 % in recent summary lines. A spinning poller takes a core from exactly the threads that would produce the value it waits for, so the shorter poll latency can come back as longer waits elsewhere. On laptops it also costs package power and boost clocks. The "tight loop
PreciseSleepUs(50)x 500" row has no Windows entry; by the per-call numbers it would be close to 100 % of a core, against a few percent onmain.The pacing callers are where a spin tail pays off:
VideoOutDriver(16.7 ms),AudioOut/Audio3d(5.3 ms) and thePreciseSleepUntildeadlines. There, 250 µs of spinning is a small share of each period and removes the overshoot. Two changes would keep that gain without the polling cost:PreciseSleepUntiland the long pacing sleeps. KeepPreciseSleepUsas a pure timer sleep for the poll loops, or give it the tail only when the request is well above the timer tick, as on Linux.WaitOnAddresson the label, or the queue's existing completion signal forWAIT_REG_MEM. That's a separate PR per caller. Spinning shouldn't stand in for it.To show the change is safe on Windows, measure total process CPU and the frame time (
aps5-summary.jsonl) for one title before and after, together with the per-call numbers. Pick a title whose queues hitWAIT_REG_MEMor that uses AudioOut2.The new median test (
< 90 µsover 31 calls) is a wall-clock bound, so it will be sensitive to a loaded CI runner and to lavapipe jobs running in parallel. If it stays, a larger sample and an opt-out on a busy runner would avoid intermittent failures that have nothing to do with the change.Imported from boykopovar/AnyPS5. Originally posted by hamb3r on 2026-10-14T20:53:32Z.
Thanks for the review @CnRJay — addressed in
ea690728c:Windows short poll loops (
PreciseSleepUs< 1000 µs):1 nscached slack +15 µstail).PreciseSleepUntildeadlines and long pacing sleeps (PreciseSleepUs>= 1000 µs, i.e.kMinTimerSpinSleepHundredNanos = 10000, well above the500 µshigh-resolution waitable timer tick) use the hybrid waitable timer +250 µsspin tail.PreciseSleepUscalls (< 1000 µs, coveringPm4.cppWAIT_REG_MEM,Apr.cppWAIT_MEM,Aio.cpp,AudioOut2Context.cpp, andFont/State.cpp) now passallowSpinTail = falseand sleep for the full duration on the waitable timer without spinning.PreciseSleepUs(50)x500loop to the PR description:251.62 mswall (503.2 µs/iter),2.11 mstotal CPU (4.22 µs/call,0.84%of a core), matchingmain(3.86 µs/call,0.75%of a core) while keepingPreciseSleepUs(1000+)andPreciseSleepUntilon-target.Median wall-clock test on loaded CI runners (
core/libs/tests/PreciseWait.cpp):31to65calls (up to 3 sample windows inCheckMedianSleepBound) and added a busy-runner opt-out (IsRunnerPreempted()scheduler-gap check +APS5_SKIP_TIMING_TESTSenv opt-out) so parallellavapipe/ loaded CI jobs won't cause spurious failures.cc @adriadam10
Imported from boykopovar/AnyPS5. Originally posted by simonbronk on 2026-10-15T07:40:41Z.
Independent Windows validation of
ea690728c32a4c6014932bca09cf971ae3d5b60d(AI-assisted), compared with the PR base84b01f9cd042e1d2e9e112f8783aa5a9d26399ee.Windows 11 build 22631, Intel Core i7-8700, WinLibs GCC 15.2.0 r7 UCRT, QPC 10 MHz. Exact
PreciseWait.hpp,HostThreadLocal.hppand PRPreciseWait.cppextracted from those commits. Standalone builds use-std=c++20 -O3 -DNDEBUG -Wall -Wextra -Werror -static -pthread.The unmodified PR test passes 3/3 runs (0.141–0.156 s);
APS5_SKIP_TIMING_TESTSis absent in the child processes, and stdout/stderr are empty (no busy-runner skip reported). This exercises the existing tick-conversion, deadline, no-early-return and invalid-timer fallback checks.An independent harness then compares both versions in three interleaved pairs (base/fixed, fixed/base, base/fixed), using normal scheduling. Each execution includes 250 short sleeps, 128 sleeps each at 1000/1500 us, 250 short deadlines, and 200 absolute deadlines at 187.5 Hz. No early return in 5,736 calls across both versions.
The table reports the median of the three per-execution medians; cycles are
QueryThreadCycleTimedeltas per call, including harness overhead, not CPU-time microseconds or a core percentage.For the 200-deadline pacing loop, total time is 1066.978 / 1066.784 ms (1066.667 ms requested). Median lateness relative to the absolute deadline is 351.9 / 90.0 us; median of per-run p99 lateness is 827.9 / 494.4 us. Individual trials vary with scheduling; these are local synthetic results.
This corroborates that the current Windows short polling path stays timer-based, while deadline/long pacing precision improves at a higher CPU-cycle cost. It does not establish acceptable whole-game CPU use or address the requested title/frame-time validation in the earlier review.
Limits: standalone native header/test execution only; no full AnyPS5/library build, CMake/CTest, title, audio playback, GPU, Linux/macOS, or current-main composition. Non-10-MHz frequencies are checked arithmetically by the PR test, not exercised as real host counters. No global timer-resolution, scheduling, power or security settings changed; no upstream source edits.
Imported from boykopovar/AnyPS5. Originally posted by github-actions[bot] on 2026-10-15T12:10:00Z.
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.cppImported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-15T13:17:31Z.
Review: APPROVED
Re-checked
ea690728cagainst the three points of the previous review:< 1000 us) are back on the plain waitable timer, and the spin tail only applies to deadlines and long pacing sleeps.prctlon the hot path.PreciseWait.cppnow asserts a median bound thatmainexceeds (PreciseSleepUs(50)~118 us on Linux vs the 90 us bound).Build and ctest are green here (105/105,
precise_waitpassed), and the independent Windows run by @simonbronk matches the claimedPreciseSleepUntilgain. Merging once the Windows build is green.Imported from boykopovar/AnyPS5. Originally posted by CnRJay on 2026-10-15T18:20:53Z.
Thanks, that resolves it. The short polls on Windows are back on the plain waitable timer, the tight-loop Windows row matches
main, and the spin tail now only serves deadlines and pacing, where it pays off. Nothing more from me.