CPU profile (WPR) on a 9800X3D: CPU saturated, busiest game thread spins in Sleep(0), list threads lose ~27% to locks #2707
Loading…
Reference in a new issue
No description provided.
Delete branch "%!s()"
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 ubiquitarianism/leonida. Originally posted by Yizzii on 2026-11-30T09:16:34Z.
CPU profile of a standing run with Windows' own profiler: the CPU is saturated, the busiest title thread mostly waits, and the list threads spend over a quarter of their time taking and releasing locks
Follow-up to #2614, with a whole-process CPU profile taken from outside the game.
Setup
bbd45f5cc, built withbuild-nvidia.ps1, started throughplay-nvidia.ps1 -Log -NoFrameGenwith its defaults (LEONIDA_GAME_ACTIONS=0)wpr -start CPU, 20 s, about 90 s into the world), converted withtracerptto CSV. Samples are about 0.57 ms apart. leonida addresses are symbolized with this build's pdb. Title addresses are image-relative at the preferred base0x140000000, so they match a disassembly of the executable.It's one 20 s recording, so treat the percentages as approximate. It started about 90 s into the world, just as the camera cut to the heavier view. According to the frame lines, the first half or so was the heavier view (about 11,200 draws a frame, 23-24 fps) and the rest the lighter one (about 5,800-5,900 draws, 28-29 fps). So the profile leans towards the heavier view.
1. The CPU is saturated
Over the 20 s, as logical CPUs busy out of 16:
Inside leonida_sm.exe, the title's own 49 threads use about 5.1 CPUs and the rest of the process (leonida's threads, plus the driver's and DirectStorage's) about 8.5, the six list threads alone 5.3. So nothing on this machine has a free core. The submitting thread, the list threads and the title's threads all compete for SMT siblings. That might explain why more helper threads didn't help here (results below).
2. The busiest title thread is mostly waiting (Sleep(0) spin)
Busiest threads of the process, in ms of CPU per second:
All the title's threads start at the image's
+0x2215ea0. That 579 ms/s title thread breaks down as:0x144fb0ad00x144fb0ad0is a wait loop. It's called through0x144fb0a90, with0x142474740,0x1424846d0,0x140c9e5e0,0x140120790and0x14011fd60above it on the stack:[vtable+0x60]) and waits until the value reaches a target (the sign ofvalue - targetat bit 55). It looks like a fence's completed value, but I haven't confirmed what it is.monitorx/mwaitx, then a call to0x144fb0e90, which isSleep(0)(a jump through the import at0x146793b98, the title'sSleep). If the two wait instructions fault on this CPU,LEONIDA_PATCH_WAITSturns them into a no-op andpause. Otherwise they run natively. I didn't check which, since the log doesn't say.0x144fb0d7conwards) calls0x14092eca0, which isSleep(1)through the same import.On the console
Sleep(0)presumably costs little. On Windows every call is a trip into the kernel, which would explain the 58% kernel time. So this thread mostly waits for whatever produces that value, and the waiting costs most of a core on a CPU with none to spare.Possible fix: recognise this loop and wait on the value instead, with a short
pausespin and thenWaitOnAddressor an event.SwitchToThreadwouldn't help, since it's also a kernel call. That should give most of a core back to the threads doing real work. Untested; it's only what the profile suggests.3. The list threads: over a quarter of their time in locks
Each
leonida-list-*thread is about 90% busy, and 70% of their samples are inside leonida_sm.exe. Of those, by innermost (inlined) function:std::sys::sync::mutex::futex::Mutex::lockstd::sys::sync::mutex::futex::Mutex::unlockstd::sys::sync::rwlock::futex::RwLock::readRwLock::read_unlockread_contendedatomic_addalloc::syncclone (Arc)That's about 38% of their time in leonida spent in lock and unlock alone, about 27% of their time overall. Most of it is the lock operations' own cost. Where a lock was actually contended (
read_contendedandlock_contended), it's about 5.6% by outermost function in the tables below. By outermost function, the biggest are:leonida_gpu::descriptor::view_atdraw::State::tablesresource::hosteddescriptor::host::placed_texturedefer_refreshdeferred_stepsdraw::State::binddescriptor::host::table_r9g9b9e5_viewsshadow::lookupSo the six list threads spend a lot of their time taking and releasing the same few locks around descriptor and resource lookups. With six threads on them, the locks' cache lines probably move between cores a lot. Fewer lock round trips per draw (or per-thread caches for
view_at) look like the biggest CPU saving in the profile. Outside leonida, their samples are mostly in nvwgf2umx.dll, D3D12.dll and D3D12Core.dll, plus some kernel time.4. The audio thread decodes Opus in software
One title thread (414 ms/s) spends about 42% of its samples in leonida_sm.exe, most of it in
leonida_hle::modules::apu::XApuEnqueueCommand→ Opus decoding (opus_pure::celt::*,opus_pure::silk::*, about 36% of its stacks) anddsp::XDspSubmitCommand/convolve::Fft::run. That's about 0.17 of a CPU. It's not on the frame's path, but it adds to the saturation.5. The submitting thread
830 ms/s. Of its samples, about 28% are in the kernel and about 16% in nvwgf2umx.dll. Of its samples inside leonida, the top ones are
leonida_safe_copy_at10%,Host::submit7%,Instant::now6%,host::copy_mapped5%, then allocations (Vec::from_iter, the allocator'sallocandrealloc,reserve_rehash, about 14% together),Shadow::nothing_new,blocked_byandstale_under_flights.Some of what the tables show looks like bookkeeping rather than work. These are small, but none of them are free on a full CPU. Percentages are of each thread's samples inside leonida:
Instant::now(6.0%) plusmul_div_u64(3.9% innermost) on the submitting thread. These are time queries, presumably for the per-frame statistics.copystat::Counting, the counting global allocator: inalloc, 4.1% of the submitting thread's samples in leonida and 1.6% of the list threads', plusrealloc.copystat::recorded: 1.8% of the list threads.core::hash::sip::Hasher::write): 1.3% of the list threads.Settings tried, and the new build vs the previous one (same spot, 4 min each)
The idle camera cuts between a lighter view (under 6,500 draws a frame) and heavier ones (over 8,000), and how much time each run spends in each differs. So besides the overall median, here are the medians for each view on its own. Frame lines between 6,500 and 8,000 draws (13 in the old build's second baseline, 2 in the new build's first, none in the others) only count in the overall median:
9e3218f0ebaseline9e3218f0ebaseline (2nd)bbd45f5ccbaselinebbd45f5ccbaseline (2nd)bbd45f5cc+LEONIDA_AHEAD_SPLIT=1bbd45f5cc+LEONIDA_AHEAD_SPLIT=1+LEONIDA_WIDE_HALF=1bbd45f5cc+LEONIDA_WIDE_HALF=1bbd45f5cc+LEONIDA_WIDE_THREADS=12bbd45f5ccbaselines. Their lower overall medians (28.3, 27.9) only come from spending more of the run in the heavier view.bbd45f5ccis slower than9e3218f0ehere, mostly in the heavier view: about 26 fps against about 29, in all six runs on the new build. In the first baseline of each build, with nearly the same draws in the heavier view (a mean of 9,775 against 9,758 a frame), the mean is 26.5 fps against 29.0. The lighter view is down about 1 fps. Per frame, the new build cuts refreshes (7.1 to 5.9 ms) and copies (10.8 to 9.5 ms), but copying back grew (7.4 to 9.6 ms).Side note: LEONIDA_PROFILE on title threads crashed the title
LEONIDA_PROFILE=200,260,2,<file>withLEONIDA_PROFILE_ONLYmatching the title's threads (leonida-image-...dll+0x2215ea) crashed the title about 2 s afterthe profile begins:unhandled exception 0xc0000005 at ntdll.dll+0x1ff2a (read 0x3: nothing mapped there). It happened once. The same profiler on leonida's own threads (LEONIDA_PROFILE_ONLY=leonida-submit) worked fine on the previous build. Probably the in-process suspend-and-unwind hitting a title thread at a bad moment. An external profiler (WPR/ETW) works fine for title threads.Tables
Symbolized with this build's pdb (
llvm-symbolizer). Percentages are of the samples in the summary line. Title addresses are function starts taken from the image's unwind table.leonida-list-0..5 together (132,674 samples in leonida_sm.exe)
By function (outermost; inlined code counted in the function it was inlined into):
leonida_gpu::descriptor::view_atleonida_gpu::draw::State::tablesthread_local with (for leonida_gpu::descriptor::host::HostHeap)leonida_gpu::resource::hosted<std::sys::sync::rwlock::futex::RwLock>::read_contendedleonida_gpu::descriptor::host::placed_texture<leonida_gpu::host::HostList>::defer_refresh<leonida_gpu::host::HostList>::deferred_stepsleonida_gpu::draw::State::bindleonida_gpu::descriptor::host::table_r9g9b9e5_viewsleonida_gpu::shadow::lookupthread_local with (for leonida_gpu::shadow::found)leonida_gpu::copystat::recorded<alloc::collections::btree::node::NodeRef>::search_tree::<leonida_gpu::host::HostList>::first_use<leonida_gpu::copystat::Counting as core::alloc::global::GlobalAlloc>::allocleonida_gpu::resource::want_level<hashbrown::map::HashMap>::insertleonida_gpu::draw::impl$13::tables::closure$3<std::sys::sync::mutex::futex::Mutex>::lock_contended<core::hash::sip::Hasher as core::hash::Hasher>::write<leonida_gpu::host::HostList>::transitionleonida_gpu::descriptor::host::buffer_srvleonida_gpu::list::with_state::<hashbrown::raw::RawTable>::reserve_rehash::By innermost (inlined) function:
std::sys::sync::mutex::futex::Mutex::lockstd::sys::sync::mutex::futex::Mutex::unlockstd::sys::sync::rwlock::futex::RwLock::readstd::sys::sync::rwlock::futex::RwLock::read_unlockcore::sync::atomic::atomic_add<std::sys::sync::rwlock::futex::RwLock>::read_contendedalloc::sync::impl$32::cloneleonida_gpu::draw::State::tablesstd::sys::sync::rwlock::futex::is_read_lockablecore::sync::atomic::Atomic::try_updatealloc::sync::impl$42::dropcore::option::Option::as_refleonida-submit (12,327 samples in leonida_sm.exe)
By function (outermost; inlined code counted in the function it was inlined into):
leonida_safe_copy_at<leonida_gpu::host::Host>::submit<std::time::Instant>::now<alloc::vec::Vec as alloc::vec::spec_from_iter_nested::SpecFromIterNested>::from_iterleonida_gpu::host::copy_mapped<leonida_gpu::shadow::Shadow>::nothing_new<leonida_gpu::copystat::Counting as core::alloc::global::GlobalAlloc>::allocleonida_gpu::host::blocked_byleonida_gpu::host::stale_under_flights<hashbrown::raw::RawTable>::reserve_rehash::<leonida_gpu::copystat::Counting as core::alloc::global::GlobalAlloc>::reallocleonida_gpu::host::declared_writes<leonida_gpu::shadow::Shadow>::merge_under_writesleonida_gpu::shadow::word_runs_avx2<alloc::collections::btree::node::NodeRef>::find_leaf_edges_spanning_range::leonida_gpu::shadow::send_copiedcore::slice::sort::stable::drift::sort::leonida_gpu::watch::Shard::notemi_malloc_alignedleonida_gpu::watch::journalleonida_gpu::host::send::take::closure$7<leonida_gpu::shadow::Shadow>::writingleonida_gpu::host::send::take<alloc::vec::Vec>::extend_desugared::leonida_gpu::host::joinable::By innermost (inlined) function:
leonida_safe_copy_atcore::sync::atomic::atomic_addcore::sync::atomic::Atomic::try_updatestd::sys::helpers::mul_div_u64std::sys::sync::mutex::futex::Mutex::unlockcore::sync::atomic::atomic_substd::sys::sync::mutex::futex::Mutex::lockalloc::sync::impl$42::dropleonida_gpu::host::declared_writesleonida_gpu::copystat::bigcore::time::Duration::from_nanosleonida_gpu::shadow::word_runs_avx2_inThe title's audio thread, its time in leonida_sm.exe (6,090 samples in leonida_sm.exe)
By function (outermost; inlined code counted in the function it was inlined into):
opus_pure::celt::bands::quant_partitionleonida_hle::modules::dsp::XDspSubmitCommand<opus_pure::celt::CeltDecoder>::decode_impl_from_rcopus_pure::silk::decode_core::silk_decode_coreleonida_hle::modules::dsp::convolve::Fft::runopus_pure::celt::kiss_fft::opus_fft_implopus_pure::celt::pvq::exp_rotation1_scalaropus_pure::silk::decode_pulses::silk_decode_pulsesopus_pure::silk::resampler::silk_resampler_private_up2_hqopus_pure::celt::mdct::MdctLookup::backward<opus_pure::decoder::OpusDecoder>::decode_nativeopus_pure::silk::decode_pulses::decode_splitopus_pure::silk::resampler::SilkResampler::iir_fir_blockopus_pure::celt::rate::clt_compute_allocationopus_pure::celt::bands::quant_all_bandsBy innermost (inlined) function:
leonida_hle::modules::dsp::convolve::Convolver::processleonida_hle::modules::dsp::convolve::Fft::runopus_pure::celt::pvq::exp_rotation1_scalaropus_pure::celt::deemphasisopus_pure::silk::macros::silk_smulwbopus_pure::celt::pvq::cwrsiopus_pure::range_coder::RangeCoder::decode_icdfopus_pure::silk::resampler::silk_resampler_private_up2_hqThe busiest title thread (the wait loop) (20,418 samples, 579 ms of CPU a second)
By module:
Title functions (start address from the image's unwind table, base
0x140000000), % of all the samples above:0x144fb0ad00x144dbf3c00x144dbda300x144dbe6900x14010a0c00x144e3b0900x144e8a9f00x144da9ec00x144f6a7c00x144da9b00The other 47 title threads together (not the audio thread) (145,608 samples, 4129 ms of CPU a second)
By module:
Title functions (start address from the image's unwind table, base
0x140000000), % of all the samples above:0x143261fd00x140096f500x1435a3b800x14258b1500x140031e300x140004b400x144d9ed600x144eea9a00x144d9d9f00x144e4af000x144d9efd00x14008eee00x144e53ef00x144f2ab600x1450705300x1401d75800x1453832900x144f738f00x1400139000x144ebd6300x14221c1f00x1426282500x144f422100x14227a3200x140110ed0Imported from ubiquitarianism/leonida. Originally posted by Yizzii on 2026-11-30T15:03:08Z.
Follow-up, same PC (RTX 5070 Ti, Ryzen 7 9800X3D), standing at the same spot, frame generation off. Sections 1 and 2 are on
d367675c7, 3 and 4 onf9f3ec4c6, 5 and 6 on20fe0c754. From section 3 on, every run hasLEONIDA_VIEW_CACHE=1(section 1).1.
LEONIDA_VIEW_CACHEhelps on this CPULEONIDA_AB(by turns of 4 s), two runs, 186 and 228 world phases. For each switch, the mean per 8-phase round of (phases on) - (phases off), with the standard error over the rounds, for the median frame time:LEONIDA_VIEW_CACHELEONIDA_CONTENT_TABLESLEONIDA_ALIAS_QUICKLEONIDA_INDEX_HEAP_SPANSd3d12/docs/findings.mdit measured +0.16 and +0.10 ms on the 4060 Ti / 7600X (d62), and +0.11 and -0.46 ms in the later repeat (d217, d218). That fits a CPU with no free core: what the list threads save goes to the threads the frame waits for.2. The title's
Sleep(0)wait (section 2 of the issue) costs no frames: ruled outSection 2 of the issue called the busiest title thread's
Sleep(0)spin a possible cost. I tested that directly, and it is not.What it is, from the disassembly:
0x2474740) the title keeps the fence points of its last two frames in a ring of two and waits for the older one, so the card is at most one frame behind.0x4fb0a50).0x4fb0a90->0x4fb0ad0) reads the fence's value at the address its slot0x60gives (fence.rsgpu_address), withmonitorx/mwaitxandSleep(0)between reads. The end-of-frame wait goes through the path withSleep(0).The test was a local patch that replaces the title's entry (
0x4fb0a90, 14-byte absolute jump, checked against the build's hash and bytes). It sleeps on the fence's value withWaitOnAddress, whichfence::set'sWakeByAddressAllalready wakes, and falls back to the title's own inner wait when turned off.LEONIDA_ABby turns, 10 min, 76 on/off triples: the median frame changed by +0.07 +-0.35 ms with the hook on.Two separate 4-min runs, median of the 5-s lines:
No effect: the median does not move, and the 0.2 fps in the heavier view is within the noise of two short runs. The same A/B's mean (-1.76 +-1.53 ms) and p90 (-1.85 +-1.70) lean negative, but each is about one standard error and far noisier than the median, as a few slow phases sway them; the submitting thread's own work changed by -0.26 +-0.17 ms. None of it is a gain I would claim. The likely reason:
Sleep(0)already gives the processor to any ready thread, so the spin's kernel time is overhead on its own thread, not a core taken from the runtime's threads. Section 3 shows what the frame does wait for. Not worth anyone's time unless a later profile shows otherwise.3. The submitting thread is not what the frame waits for here
LEONIDA_TIMELINE(20 frames at 200 s, 30.5 ms a frame) andLEONIDA_PROFILEonleonida-submit(every 2 ms, 200-260 s, 23,204 samples), separate runs. I did not check which of the two views the 20 frames fell in.The chain back through all frames, per frame, by cause:
leonida-submitran 22.1 ms and waited 8.9 ms of each 30.5 ms frame.Where
leonida-submitspends its samples (inclusive):wait_on_address(9.1 % of all samples insideshadow::wide, waiting for helpers; the rest outside it)shadow::wide(the work spread over threads, its own share included)submit, of which about 8 % iswatch::kernel_written(6.8 % throughwatch::ask_ahead), inntdllBatch::refresh_frontBatch::fillcard_before(closure)The NVIDIA driver is the top module for 12.7 % of all samples. So with the view cache on, the submitting thread waits 8.9 ms a frame; taking out its waits for helpers, about 5 to 6 ms of that is slack. The chain is the title's own threads and the list threads' recording.
4. List threads: half their time is table setup for indirect executions
LEONIDA_PROFILEonleonida-list(every 2 ms, 200-260 s, 138,480 samples over the six threads). Inclusive shares:State::bind(all callers)list::execute_indirectclosureState::tablesHostHeap::make_listedmake_twinned_info(4.1 % in the driver'sCreateShaderResourceView)draw::readablekeep_refMutex::lock6.9 % self,Mutex::unlock2.6 %,RwLock::read1.4 %. About 11 % in all, well under the ETW figure in the issue (about 27 %). The two tools count differently, so I would not call that a measured drop.State::tables(draw.rs, thelisted_viewbranch):list.deferred_steps()takes the list'sdeferredmutex only to readcopies.len(), for each view not yet known ready. That is 1.9 % of the list threads' samples.D3D12Core4.6 %,d3d123.3 %.5. Two local experiments on the list threads: no measurable gain
Both behind switches, off by default, measured with
LEONIDA_ABin one 10-min run (4 s turns, 152 world phases, 37 complete rounds of 4). Median frame time, on minus off:deferred_steps()without the lockmake_listedclears a thread'sListViewsat every new recording. With the switch, a thread kept them for up to 512 recordings, or until three quarters of the slots were used. It used one again only for a plainView::Shaderof a title texture, only ifmade_copygave the same host copy (Weakpointer compare) and the first level shown was the same, and withlisted.ready,tabledandaliasedreset. Every other view was made anew as now, in a new slot. Used again: 16.5 million; made anew: 31.9 million. So about a third reused, and the frame did not move. My guess is that most of the rest are placed-memory views, which this left alone, but I did not count by kind. In the part of the run I watched there was nothing beyond the usual flicker.deferred_steps()without the lock. The list's step count is stored in an atomic as thedeferredguard is dropped, under the lock, anddeferred_steps()reads that. Nothing measurable.The list threads' cost is spread thin: no single part of it moves the frame on its own here.
6.
20fe0c754(pools grown with their lock released)A 6-min run standing, 5-s frame lines split by view:
20fe0c754f9f3ec4c6, profile run (sampler on)f9f3ec4c6, timeline runNo change in frame time, as expected. Its own line for the run: 79 blocks made in 288 ms (longest 24.3 ms), and 977 waits for their pools, 2 ms in all (longest 0.6 ms). Before this change a thread that wanted the pool while a block was being made waited behind its lock; now those waits came to 2 ms in all. If that shows anywhere it should be as fewer hitches, not in the 5-s medians.
Imported from ubiquitarianism/leonida. Originally posted by zmasi on 2026-11-30T16:41:39Z.
Opened #2764 addressing the four list-thread lock contention hotspots in section 3 (
descriptor::view_at,descriptor::host::table_r9g9b9e5_views,descriptor::host::placed_texture/resource::texture_at+resource::want_level, andresource::hosted) behindLEONIDA_LIST_LOCK_FAST(on by default;=0negative control):300.0 -> 31.3 ns/draw(9.60x)no-r9and301.8 -> 45.1 ns/draw(6.69x) combined across 6 recording threads.AI-assisted: GPT-6.2 Astra and Claude / Gemini 4 Neon, verified with Gemini 4 Carbon (High), reviewed with Gemini 4 Neon (XHigh).