upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/src/thread_sampler.h
diff options
context:
space:
mode:
authorAndretuta <Andretuta@users.noreply.github.com>2026-11-25 18:33:16 -0300
committerAndretuta <Andretuta@users.noreply.github.com>2026-11-25 18:33:16 -0300
commitadf9c3f20bbb6f7685770b301719bc7e4c357507 (patch)
tree178d820b89deaace44dd963c7f9c4ee1cad50a31 /runtime/src/thread_sampler.h
parent7430be3869d72fda88796f00efaacb7f1f965e71 (diff)
parent4eab4f6d34b61d9c66d54308a7af2b56539339a1 (diff)
Merge main into gpu/rx9070xt-refresh
Keep this branch's RX 9070 XT row and the rows main added below it (RX 9070, Ryzen 5 7600X iGPU, RTX 5070 Ti, RTX 3080). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime/src/thread_sampler.h')
-rw-r--r--runtime/src/thread_sampler.h404
1 files changed, 404 insertions, 0 deletions
diff --git a/runtime/src/thread_sampler.h b/runtime/src/thread_sampler.h
new file mode 100644
index 000000000..282eb20dd
--- /dev/null
+++ b/runtime/src/thread_sampler.h
@@ -0,0 +1,404 @@
1#pragma once
2// LEONIDA_SAMPLE_MS=<ms> (diagnostic, off by default): where the process's busy threads spend their CPU, without a
3// debugger or perf. A thread wakes every <ms>, and for each thread of the process that used CPU since its last look
4// suspends it, copies its context and resumes it at once; the stack is then unwound outside the suspension (through
5// the .pdata every module registers, the title's included), under __try, since the thread runs on meanwhile. Every
6// LEONIDA_SAMPLE_REPORT_S seconds (10) one block lists the busiest threads (CPU share) and the most frequent call
7// chains (up to eight frames, innermost first): title frames as t+RVA of the function, others as module+RVA. Nothing is
8// allocated or logged while a thread is suspended, so a suspended thread's locks are never waited for.
9#ifndef NOMINMAX
10#define NOMINMAX
11#endif
12#include <windows.h>
13#include <tlhelp32.h>
14
15#include <algorithm>
16#include <array>
17#include <cstdint>
18#include <cstdio>
19#include <cstdlib>
20#include <map>
21#include <string>
22#include <vector>
23
24#include "submit_phases.h"
25
26namespace leonida::thread_sampler {
27
28constexpr int kFrames = 8;
29using Chain = std::array<std::uint64_t, kFrames>; // function starts (or addresses), innermost first
30// LEONIDA_SAMPLE_SHIMS=1 (with LEONIDA_SAMPLE_MS): each sample is unwound this deep to tell whether a title thread
31// is inside our runtime (a frame of this executable called, at any depth, from title code), and where.
32constexpr int kDeepFrames = 48;
33using DeepChain = std::array<std::uint64_t, kDeepFrames>;
34
35
36struct Sampler {
37 std::uint8_t* title = nullptr;
38 std::uint64_t title_size = 0;
39 DWORD period_ms = 10;
40 DWORD report_ms = 10000;
41 bool waits = false; // LEONIDA_SAMPLE_WAITS=1: every thread, busy or waiting (where the wall time goes)
42 bool shims = false; // LEONIDA_SAMPLE_SHIMS=1: per title thread, the share of its samples inside our runtime
43 std::uint64_t self_base = 0, self_size = 0; // this executable (the runtime)
44 // LEONIDA_SAMPLE_DETAIL=<id>[,<id>...]: for these threads, the 10 most frequent chains, 16 frames deep, each as a
45 // share of that thread's samples (thread ids are stable from boot to boot: the title's main, render and submit).
46 std::vector<DWORD> detail;
47};
48
49// Per title thread (one with a title frame in its chain): how many samples were inside our runtime, and through which
50// entry (the runtime frame the title called) and which runtime function was innermost.
51struct ShimCounts {
52 std::uint64_t title = 0; // samples with a title frame
53 std::uint64_t ours = 0; // ... of which inside our runtime
54 std::uint64_t ours_busy = 0; // ... while the thread used CPU since the previous look
55 std::uint64_t busy = 0; // samples with a title frame while the thread used CPU
56 std::map<std::pair<std::uint64_t, std::uint64_t>, std::uint64_t> entries; // (our entry, title caller) -> samples
57 std::map<std::uint64_t, std::uint64_t> inner; // innermost runtime function -> samples
58 std::map<std::uint64_t, std::uint64_t> leaves; // innermost frame (any module) -> samples
59};
60
61// Classifies one deep chain (innermost first) for LEONIDA_SAMPLE_SHIMS.
62inline void count_shims(const Sampler& s, const DeepChain& chain, int n, bool moved, ShimCounts& c) {
63 const auto title = reinterpret_cast<std::uint64_t>(s.title);
64 const auto in_title = [&](std::uint64_t a) { return a >= title && a < title + s.title_size; };
65 const auto in_self = [&](std::uint64_t a) { return a >= s.self_base && a < s.self_base + s.self_size; };
66 int first_title = -1;
67 for (int i = 0; i < n; ++i)
68 if (in_title(chain[i])) {
69 first_title = i;
70 break;
71 }
72 if (first_title < 0) return;
73 ++c.title;
74 c.busy += moved;
75 int entry = -1, innermost = -1;
76 for (int i = 0; i < first_title; ++i)
77 if (in_self(chain[i])) {
78 if (innermost < 0) innermost = i;
79 entry = i; // the outermost runtime frame below the title's
80 }
81 if (entry < 0) return;
82 ++c.ours;
83 c.ours_busy += moved;
84 ++c.entries[{chain[entry], chain[first_title]}];
85 ++c.inner[chain[innermost]];
86 ++c.leaves[chain[0]];
87}
88
89// The chain of a context copied from a suspended thread: unwound under __try (its stack may be changing).
90template <std::size_t N>
91inline int unwind(CONTEXT context, std::array<std::uint64_t, N>& chain) {
92 int n = 0;
93 __try {
94 for (; n < int(N); ++n) {
95 const DWORD64 pc = context.Rip;
96 if (!pc) break;
97 DWORD64 image = 0;
98 PRUNTIME_FUNCTION entry = RtlLookupFunctionEntry(pc, &image, nullptr);
99 chain[n] = entry ? image + entry->BeginAddress : pc;
100 if (!entry) { // a leaf, or code with no unwind data: take the return address at the stack pointer
101 context.Rip = *reinterpret_cast<const DWORD64*>(context.Rsp);
102 context.Rsp += 8;
103 continue;
104 }
105 void* handler_data = nullptr;
106 DWORD64 frame = 0;
107 RtlVirtualUnwind(UNW_FLAG_NHANDLER, image, pc, entry, &context, &handler_data, &frame, nullptr);
108 }
109 } __except (EXCEPTION_EXECUTE_HANDLER) {
110 }
111 return n;
112}
113
114inline std::string name_of(const Sampler& s, std::uint64_t at) {
115 char text[96];
116 const auto title = reinterpret_cast<std::uint64_t>(s.title);
117 if (at >= title && at < title + s.title_size) {
118 std::snprintf(text, sizeof(text), "t+%llx", static_cast<unsigned long long>(at - title));
119 return text;
120 }
121 HMODULE module = nullptr;
122 if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
123 reinterpret_cast<LPCWSTR>(at), &module) &&
124 module) {
125 wchar_t path[MAX_PATH] = {};
126 GetModuleFileNameW(module, path, MAX_PATH);
127 const wchar_t* base = path;
128 for (const wchar_t* p = path; *p; ++p)
129 if (*p == L'\\' || *p == L'/') base = p + 1;
130 std::snprintf(text, sizeof(text), "%ls+%llx", base,
131 static_cast<unsigned long long>(at - reinterpret_cast<std::uint64_t>(module)));
132 return text;
133 }
134 std::snprintf(text, sizeof(text), "0x%llx", static_cast<unsigned long long>(at));
135 return text;
136}
137
138inline DWORD WINAPI run(LPVOID parameter) {
139 const Sampler s = *static_cast<Sampler*>(parameter);
140 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
141 const DWORD self = GetCurrentThreadId(), pid = GetCurrentProcessId();
142 struct Thread {
143 HANDLE handle = nullptr;
144 std::uint64_t cpu = 0; // 100 ns, at the last look
145 std::uint64_t used = 0; // since the last report
146 std::uint64_t samples = 0;
147 };
148 std::map<DWORD, Thread> threads;
149 std::map<std::pair<DWORD, Chain>, std::uint64_t> chains;
150 std::map<DWORD, ShimCounts> shim_counts;
151 constexpr int kDetailFrames = 16;
152 using DetailChain = std::array<std::uint64_t, kDetailFrames>;
153 std::map<std::pair<DWORD, DetailChain>, std::uint64_t> detail_chains;
154 std::uint64_t total = 0;
155 ULONGLONG listed = 0, reported = GetTickCount64();
156 const auto cpu_of = [](HANDLE h) {
157 FILETIME created{}, exited{}, kernel{}, user{};
158 if (!GetThreadTimes(h, &created, &exited, &kernel, &user)) return std::uint64_t(0);
159 const auto ticks = [](const FILETIME& f) { return (std::uint64_t(f.dwHighDateTime) << 32) | f.dwLowDateTime; };
160 return ticks(kernel) + ticks(user);
161 };
162 for (;;) {
163 Sleep(s.period_ms);
164 const ULONGLONG now = GetTickCount64();
165 if (now - listed >= 2000) { // the thread list, every 2 s
166 listed = now;
167 const HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
168 if (snap != INVALID_HANDLE_VALUE) {
169 THREADENTRY32 e{sizeof(e)};
170 for (BOOL ok = Thread32First(snap, &e); ok; ok = Thread32Next(snap, &e)) {
171 if (e.th32OwnerProcessID != pid || e.th32ThreadID == self || threads.count(e.th32ThreadID)) continue;
172 const HANDLE h = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION,
173 FALSE, e.th32ThreadID);
174 if (h) threads[e.th32ThreadID] = {h, cpu_of(h)};
175 e.dwSize = sizeof(e);
176 }
177 CloseHandle(snap);
178 }
179 }
180 for (auto it = threads.begin(); it != threads.end();) {
181 Thread& t = it->second;
182 const std::uint64_t cpu = cpu_of(t.handle);
183 DWORD code = 0;
184 if (GetExitCodeThread(t.handle, &code) && code != STILL_ACTIVE) {
185 CloseHandle(t.handle);
186 it = threads.erase(it);
187 continue;
188 }
189 const bool moved = cpu != t.cpu;
190 const bool busy = moved || s.waits;
191 t.used += cpu - t.cpu;
192 t.cpu = cpu;
193 if (busy) {
194 CONTEXT context{};
195 context.ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER;
196 bool got = false;
197 if (SuspendThread(t.handle) != DWORD(-1)) {
198 got = GetThreadContext(t.handle, &context) != FALSE;
199 ResumeThread(t.handle);
200 }
201 if (got) {
202 Chain chain{};
203 if (std::find(s.detail.begin(), s.detail.end(), it->first) != s.detail.end()) {
204 DetailChain deep{};
205 unwind(context, deep);
206 ++detail_chains[{it->first, deep}];
207 }
208 if (s.shims) {
209 DeepChain deep{};
210 const int n = unwind(context, deep);
211 std::copy_n(deep.begin(), kFrames, chain.begin());
212 count_shims(s, deep, n, moved, shim_counts[it->first]);
213 } else {
214 unwind(context, chain);
215 }
216 ++chains[{it->first, chain}];
217 ++t.samples;
218 ++total;
219 }
220 }
221 ++it;
222 }
223 if (now - reported < s.report_ms || !total) continue;
224 const double seconds = double(now - reported) / 1000.0;
225 reported = now;
226 std::vector<std::pair<std::uint64_t, DWORD>> busiest;
227 for (auto& [id, t] : threads)
228 if (t.used) busiest.emplace_back(t.used, id);
229 std::sort(busiest.rbegin(), busiest.rend());
230 std::string line;
231 for (std::size_t i = 0; i < busiest.size() && i < 8; ++i) {
232 char text[64];
233 std::snprintf(text, sizeof(text), "%s%lu %.0f%%", i ? ", " : "", busiest[i].second,
234 double(busiest[i].first) * 1e-5 / seconds);
235 line += text;
236 }
237 std::fprintf(stderr, "[rt] sampler: %llu samples in %.0f s; CPU by thread: %s\n",
238 static_cast<unsigned long long>(total), seconds, line.c_str());
239 std::vector<std::pair<std::uint64_t, const std::pair<DWORD, Chain>*>> top;
240 for (const auto& c : chains) top.emplace_back(c.second, &c.first);
241 std::sort(top.begin(), top.end(), [](const auto& a, const auto& b) { return a.first > b.first; });
242 const auto print = [&](const auto& entry, std::uint64_t of, const char* what) {
243 std::string frames;
244 for (int f = 0; f < kFrames && entry.second->second[f]; ++f)
245 frames += (f ? " < " : "") + name_of(s, entry.second->second[f]);
246 std::fprintf(stderr, "[rt] sampler: %s %5.1f%% thread %lu: %s\n", what, 100.0 * double(entry.first) / double(of),
247 entry.second->first, frames.c_str());
248 };
249 for (std::size_t i = 0; i < top.size() && i < 16; ++i) print(top[i], total, " ");
250 // Apart: the submitting thread's chains, and the two busiest threads', each as a share of that thread's samples.
251 std::vector<DWORD> apart;
252 if (const DWORD submitter = submit_phases::totals().thread.load(std::memory_order_relaxed)) apart.push_back(submitter);
253 for (std::size_t i = 0; i < busiest.size() && i < 2; ++i)
254 if (std::find(apart.begin(), apart.end(), busiest[i].second) == apart.end()) apart.push_back(busiest[i].second);
255 // With waiting threads sampled: each thread's own most frequent chain, busiest first, so a thread that waits
256 // (the title's main thread behind its render thread, a render thread behind a lock) shows where.
257 if (s.waits) {
258 std::vector<std::pair<std::uint64_t, DWORD>> all;
259 for (auto& [id, t] : threads)
260 if (t.samples) all.emplace_back(t.used, id);
261 std::sort(all.rbegin(), all.rend());
262 std::size_t listed = 0;
263 for (const auto& [used, id] : all) {
264 if (listed++ >= 24) break;
265 const auto it = threads.find(id);
266 if (it == threads.end() || !it->second.samples) continue;
267 for (const auto& entry : top)
268 if (entry.second->first == id) {
269 print(entry, it->second.samples, "thread");
270 break;
271 }
272 }
273 }
274 for (const DWORD id : apart) {
275 const auto it = threads.find(id);
276 if (it == threads.end() || !it->second.samples) continue;
277 std::size_t shown = 0;
278 for (const auto& entry : top)
279 if (entry.second->first == id && shown++ < 8)
280 print(entry, it->second.samples, id == apart.front() && submit_phases::totals().thread.load() == id
281 ? "submit"
282 : "busy ");
283 }
284 for (const DWORD id : s.detail) {
285 std::vector<std::pair<std::uint64_t, const DetailChain*>> mine;
286 std::uint64_t all = 0;
287 for (const auto& [key, n] : detail_chains)
288 if (key.first == id) {
289 mine.emplace_back(n, &key.second);
290 all += n;
291 }
292 std::sort(mine.begin(), mine.end(), [](const auto& a, const auto& b) { return a.first > b.first; });
293 for (std::size_t i = 0; i < mine.size() && i < 10; ++i) {
294 std::string frames;
295 for (int f = 0; f < kDetailFrames && (*mine[i].second)[f]; ++f)
296 frames += (f ? " < " : "") + name_of(s, (*mine[i].second)[f]);
297 std::fprintf(stderr, "[rt] sampler: detail thread %lu %5.1f%%: %s\n", id,
298 100.0 * double(mine[i].first) / double(all), frames.c_str());
299 }
300 }
301 detail_chains.clear();
302 if (s.shims) {
303 // Title threads by their samples inside our runtime: where the title's own threads (its main, render and
304 // Subrender workers, streaming) spend time in our shims, waiting or running.
305 const auto top_of = [&](const auto& counts, std::size_t limit, bool pair_key) {
306 std::vector<std::pair<std::uint64_t, std::string>> v;
307 for (const auto& [key, n] : counts) {
308 std::string name;
309 if constexpr (requires { key.first; }) {
310 name = name_of(s, key.first) + "<-" + name_of(s, key.second);
311 } else {
312 name = name_of(s, key);
313 }
314 v.emplace_back(n, std::move(name));
315 }
316 (void)pair_key;
317 std::sort(v.begin(), v.end(), [](const auto& a, const auto& b) { return a.first > b.first; });
318 std::string text;
319 for (std::size_t i = 0; i < v.size() && i < limit; ++i) {
320 char n[24];
321 std::snprintf(n, sizeof(n), " %llu", static_cast<unsigned long long>(v[i].first));
322 text += (i ? ", " : "") + v[i].second + n;
323 }
324 return text;
325 };
326 std::vector<std::pair<std::uint64_t, DWORD>> order;
327 ShimCounts all;
328 for (const auto& [id, c] : shim_counts) {
329 if (!c.title) continue;
330 order.emplace_back(c.ours, id);
331 all.title += c.title;
332 all.ours += c.ours;
333 all.ours_busy += c.ours_busy;
334 all.busy += c.busy;
335 for (const auto& [k, n] : c.entries) all.entries[k] += n;
336 for (const auto& [k, n] : c.inner) all.inner[k] += n;
337 for (const auto& [k, n] : c.leaves) all.leaves[k] += n;
338 }
339 std::sort(order.rbegin(), order.rend());
340 std::fprintf(stderr, "[rt] sampler: shims: title-thread samples inside our runtime %llu of %llu (%.1f%%), "
341 "%llu of them while the thread used CPU\n",
342 static_cast<unsigned long long>(all.ours), static_cast<unsigned long long>(all.title),
343 all.title ? 100.0 * double(all.ours) / double(all.title) : 0.0,
344 static_cast<unsigned long long>(all.ours_busy));
345 for (std::size_t i = 0; i < order.size() && i < 12 && order[i].first; ++i) {
346 const ShimCounts& c = shim_counts[order[i].second];
347 std::fprintf(stderr, "[rt] sampler: shims thread %lu: %llu of %llu samples ours (%.0f%%; %llu busy), "
348 "thread busy in %llu; entries: %s; innermost ours: %s; leaves: %s\n",
349 order[i].second, static_cast<unsigned long long>(c.ours),
350 static_cast<unsigned long long>(c.title), 100.0 * double(c.ours) / double(c.title),
351 static_cast<unsigned long long>(c.ours_busy), static_cast<unsigned long long>(c.busy),
352 top_of(c.entries, 5, true).c_str(), top_of(c.inner, 5, false).c_str(),
353 top_of(c.leaves, 3, false).c_str());
354 }
355 std::fprintf(stderr, "[rt] sampler: shims all: entries: %s\n", top_of(all.entries, 16, true).c_str());
356 std::fprintf(stderr, "[rt] sampler: shims all: innermost ours: %s\n", top_of(all.inner, 16, false).c_str());
357 std::fprintf(stderr, "[rt] sampler: shims all: leaves: %s\n", top_of(all.leaves, 12, false).c_str());
358 shim_counts.clear();
359 }
360 chains.clear();
361 total = 0;
362 for (auto& [id, t] : threads) t.used = t.samples = 0;
363 }
364}
365
366// From main, once the title is mapped. Does nothing without LEONIDA_SAMPLE_MS.
367inline void start(std::uint8_t* title, std::uint64_t title_size) {
368 char text[16] = {};
369 const DWORD n = GetEnvironmentVariableA("LEONIDA_SAMPLE_MS", text, sizeof(text));
370 if (!n || n >= sizeof(text)) return;
371 static Sampler s;
372 s.title = title;
373 s.title_size = title_size;
374 s.period_ms = (std::max)(1ul, std::strtoul(text, nullptr, 10));
375 char report[16] = {};
376 if (GetEnvironmentVariableA("LEONIDA_SAMPLE_REPORT_S", report, sizeof(report)) > 0)
377 s.report_ms = (std::max)(1ul, std::strtoul(report, nullptr, 10)) * 1000;
378 char waits[4] = {};
379 s.waits = GetEnvironmentVariableA("LEONIDA_SAMPLE_WAITS", waits, sizeof(waits)) == 1 && waits[0] == '1';
380 char detail[128] = {};
381 if (const DWORD n = GetEnvironmentVariableA("LEONIDA_SAMPLE_DETAIL", detail, sizeof(detail)); n && n < sizeof(detail))
382 for (char* at = detail; *at;) {
383 char* end = nullptr;
384 const unsigned long id = std::strtoul(at, &end, 10);
385 if (end == at) break;
386 if (id) s.detail.push_back(DWORD(id));
387 at = *end == ',' ? end + 1 : end;
388 }
389 char shims[4] = {};
390 s.shims = GetEnvironmentVariableA("LEONIDA_SAMPLE_SHIMS", shims, sizeof(shims)) == 1 && shims[0] == '1';
391 if (const auto self = reinterpret_cast<const std::uint8_t*>(GetModuleHandleW(nullptr))) {
392 const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(self);
393 const auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS64*>(self + dos->e_lfanew);
394 s.self_base = reinterpret_cast<std::uint64_t>(self);
395 s.self_size = nt->OptionalHeader.SizeOfImage;
396 }
397 if (const HANDLE h = CreateThread(nullptr, 0, &run, &s, 0, nullptr)) {
398 CloseHandle(h);
399 std::fprintf(stderr, "[rt] sampler: every %lu ms, report every %lu s%s%s\n", s.period_ms, s.report_ms / 1000,
400 s.waits ? ", waiting threads too" : "", s.shims ? ", title threads inside our runtime" : "");
401 }
402}
403
404} // namespace leonida::thread_sampler