Files
EonaCat.XSBox/crates/graphics/src/cores.rs
T
EonaCat 53e6e612c9
Rust validation / Formatting (push) Failing after 26s
EonaCat/ci-workflows: SonarQube / sonar (push) Successful in 47s
Rust validation / Windows x64 build and tests (push) Canceled after 0s
Initial
2026-12-04 21:27:30 +01:00

616 lines
25 KiB
Rust

fn cpu_sets() -> Vec<(u32, u8, u8, u8)> {
use windows_sys::Win32::System::SystemInformation::{GetSystemCpuSetInformation, SYSTEM_CPU_SET_INFORMATION};
use windows_sys::Win32::System::Threading::GetCurrentProcess;
let mut bytes = 0u32;
unsafe { GetSystemCpuSetInformation(std::ptr::null_mut(), 0, &mut bytes, GetCurrentProcess(), 0) };
let mut buffer = vec![0u64; (bytes as usize).div_ceil(8).max(1)];
let ok = unsafe { GetSystemCpuSetInformation(buffer.as_mut_ptr().cast(), bytes, &mut bytes, GetCurrentProcess(), 0) };
let mut sets = Vec::new();
let mut at = 0usize;
while ok != 0 && at + size_of::<SYSTEM_CPU_SET_INFORMATION>() <= bytes as usize {
let info = unsafe { &*(buffer.as_ptr().cast::<u8>().add(at).cast::<SYSTEM_CPU_SET_INFORMATION>()) };
if info.Size == 0 {
break;
}
let set = unsafe { &info.Anonymous.CpuSet };
if set.Group == 0 {
sets.push((set.Id, set.EfficiencyClass, set.LogicalProcessorIndex, set.CoreIndex));
}
at += info.Size as usize;
}
sets
}
fn fast_of(sets: &[(u32, u8)]) -> Vec<u32> {
let best = sets.iter().map(|c| c.1).max().unwrap_or(0);
let fast: Vec<u32> = sets.iter().filter(|c| c.1 == best).map(|c| c.0).collect();
if fast.len() == sets.len() { Vec::new() } else { fast }
}
fn fast_from(sets: &[(u32, u8, u8, u8)], from: u8) -> Vec<u32> {
let classes: Vec<(u32, u8)> = sets.iter().map(|c| (c.0, c.1)).collect();
let fast = fast_of(&classes);
sets.iter().filter(|c| c.2 >= from && fast.contains(&c.0)).map(|c| c.0).collect()
}
fn last_level_caches() -> Vec<(usize, u32)> {
use windows_sys::Win32::System::SystemInformation::{
CACHE_RELATIONSHIP, GetLogicalProcessorInformationEx, RelationCache, SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX,
};
let mut bytes = 0u32;
unsafe { GetLogicalProcessorInformationEx(RelationCache, std::ptr::null_mut(), &mut bytes) };
let mut buffer = vec![0u64; (bytes as usize).div_ceil(8).max(1)];
let ok = unsafe { GetLogicalProcessorInformationEx(RelationCache, buffer.as_mut_ptr().cast(), &mut bytes) };
let (start, bytes) = (buffer.as_ptr().cast::<u8>(), bytes as usize);
let body = std::mem::offset_of!(SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX, Anonymous);
let mut caches: Vec<(u8, usize, u32)> = Vec::new();
let mut at = 0usize;
while ok != 0 && at + body <= bytes {
let (relationship, size) = unsafe { (start.add(at).cast::<i32>().read_unaligned(), start.add(at + 4).cast::<u32>().read_unaligned() as usize) };
if size == 0 || at + size > bytes {
break;
}
if relationship == RelationCache && size >= body + size_of::<CACHE_RELATIONSHIP>() {
let (cache, mask) = unsafe {
let cache = start.add(at + body).cast::<CACHE_RELATIONSHIP>().read_unaligned();
(cache, cache.Anonymous.GroupMask)
};
if mask.Group == 0 {
caches.push((cache.Level, mask.Mask, cache.CacheSize));
}
}
at += size;
}
let last = caches.iter().map(|c| c.0).max().unwrap_or(0);
caches.into_iter().filter(|c| c.0 == last).map(|c| (c.1, c.2)).collect()
}
fn big_cache_of(sets: &[(u32, u8)], caches: &[(usize, u32)]) -> Vec<u32> {
let most = caches.iter().map(|c| c.1).max().unwrap_or(0);
let under = caches.iter().filter(|c| c.1 == most).fold(0usize, |all, c| all | c.0);
let big: Vec<u32> = sets.iter().filter(|s| u32::from(s.1) < usize::BITS && under >> s.1 & 1 != 0).map(|s| s.0).collect();
if big.len() == sets.len() { Vec::new() } else { big }
}
fn split(sets: &[(u32, u8, u8, u8)], caches: &[(usize, u32)]) -> Option<(Vec<u32>, Vec<u32>)> {
let classes: Vec<(u32, u8)> = sets.iter().map(|s| (s.0, s.1)).collect();
if !fast_of(&classes).is_empty() {
return None;
}
let places: Vec<(u32, u8)> = sets.iter().map(|s| (s.0, s.2)).collect();
let big = big_cache_of(&places, caches);
let rest: Vec<u32> = places.iter().map(|p| p.0).filter(|id| !big.contains(id)).collect();
(big.len() >= 16 && big.len() >= rest.len()).then_some((big, rest))
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum SubmitCore {
Off,
VcacheCore,
OtherCore,
}
fn submit_core_mode() -> SubmitCore {
static MODE: std::sync::OnceLock<SubmitCore> = std::sync::OnceLock::new();
*MODE.get_or_init(|| match std::env::var("EONACAT_XS_SUBMIT_CORE").ok().as_deref().map(str::trim) {
Some("0") => SubmitCore::Off,
Some("ccd1") | Some("other") => SubmitCore::OtherCore,
_ => SubmitCore::VcacheCore,
})
}
fn carve_core(sets: &[(u32, u8, u8, u8)], group: &[u32]) -> Option<(u32, Vec<u32>)> {
let &(primary_id, _, _, core_idx) = sets.iter().find(|s| group.contains(&s.0))?;
let others: Vec<u32> = sets
.iter()
.filter(|s| group.contains(&s.0) && s.3 != core_idx)
.map(|s| s.0)
.collect();
(!others.is_empty()).then_some((primary_id, others))
}
fn split_from(sets: &[(u32, u8, u8, u8)], caches: &[(usize, u32)], least: usize) -> Option<(Vec<u32>, Vec<u32>)> {
let classes: Vec<(u32, u8)> = sets.iter().map(|s| (s.0, s.1)).collect();
if !fast_of(&classes).is_empty() {
return None;
}
let places: Vec<(u32, u8)> = sets.iter().map(|s| (s.0, s.2)).collect();
let big = big_cache_of(&places, caches);
let rest: Vec<u32> = places.iter().map(|p| p.0).filter(|id| !big.contains(id)).collect();
(big.len() >= least && !rest.is_empty() && big.len() >= rest.len()).then_some((big, rest))
}
fn keep_translators_off_the_cache(what: &str) {
use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadSelectedCpuSets};
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
if !*ON.get_or_init(|| std::env::var("EONACAT_XS_THIN_CORES").is_ok_and(|v| v.trim() == "other")) {
return;
}
static HALVES: std::sync::OnceLock<Option<(Vec<u32>, Vec<u32>)>> = std::sync::OnceLock::new();
let Some((_, rest)) = HALVES
.get_or_init(|| {
let h = split_from(&cpu_sets(), &last_level_caches(), 8);
match &h {
Some((big, rest)) => tracing::info!(cache = big.len(), other = rest.len(), "list translators on the half without the larger cache (EONACAT_XS_THIN_CORES=other)"),
None => tracing::info!("EONACAT_XS_THIN_CORES=other: no half with a larger cache found; translators left to the scheduler"),
}
h
})
.as_ref()
else {
return;
};
if unsafe { SetThreadSelectedCpuSets(GetCurrentThread(), rest.as_ptr(), rest.len() as u32) } == 0 {
tracing::warn!(what, error = %std::io::Error::last_os_error(), "a translator could not be kept off the cache half");
}
}
fn halves() -> Option<&'static (Vec<u32>, Vec<u32>)> {
static HALVES: std::sync::OnceLock<Option<(Vec<u32>, Vec<u32>)>> = std::sync::OnceLock::new();
HALVES.get_or_init(|| split(&cpu_sets(), &last_level_caches())).as_ref()
}
static PLACED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
static SUBMIT_SET: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
static PROCESS_SETS: std::sync::OnceLock<Vec<u32>> = std::sync::OnceLock::new();
pub(crate) fn place_process() {
use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetProcessAffinityMask, SetProcessDefaultCpuSets};
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| {
let Some((big, rest)) = halves() else {
tracing::info!("no larger cache on a part of 16 logical processors or more: the process is not placed");
carve_submit_core_alone();
return;
};
let sets = cpu_sets();
let mode = submit_core_mode();
let (proc_sets, carved) = match mode {
SubmitCore::VcacheCore => match carve_core(&sets, big) {
Some((id, others)) => (others, Some(id)),
None => (big.clone(), None),
},
SubmitCore::OtherCore => (big.clone(), carve_core(&sets, rest).map(|(id, _)| id)),
SubmitCore::Off => (big.clone(), None),
};
let lps = sets.iter().filter(|s| proc_sets.contains(&s.0)).fold(0usize, |m, s| m | 1 << s.2);
let every = sets.iter().fold(0usize, |m, s| m | 1 << s.2);
let on = format!("{lps:#x}");
if std::env::var_os("EONACAT_XS_CACHE_CORES").is_none_or(|v| v != "1") {
tracing::info!(on, "the process is not put on the logical processors under the larger cache (EONACAT_XS_CACHE_CORES=1: it is)");
return;
}
let (mut ours, mut all) = (0usize, 0usize);
if unsafe { GetProcessAffinityMask(GetCurrentProcess(), &mut ours, &mut all) } != 0 && ours & every != every {
tracing::warn!(on, mask = %format!("{ours:#x}"), "the process was started with an affinity mask: it is not placed");
return;
}
if unsafe { SetProcessDefaultCpuSets(GetCurrentProcess(), proc_sets.as_ptr(), proc_sets.len() as u32) } == 0 {
tracing::warn!(error = %std::io::Error::last_os_error(), "the process could not be put on the larger cache's processors");
return;
}
let _ = PROCESS_SETS.set(proc_sets);
if let Some(id) = carved {
SUBMIT_SET.store(id, std::sync::atomic::Ordering::Release);
}
PLACED.store(true, std::sync::atomic::Ordering::Release);
tracing::info!(
on,
others = rest.len(),
submit_core = ?mode,
submit_set = carved.unwrap_or(0),
"the process runs on the logical processors under the larger cache, pipeline makers, DirectStorage and the runtime's background compiles on the others (EONACAT_XS_CACHE_CORES=1)"
);
let watch = std::thread::Builder::new().name("eonacat-xs-cores".to_owned()).spawn(|| {
keep_off_the_frames_cores("eonacat-xs-cores");
loop {
keep_runtime_compiles_off_the_frames_cores();
std::thread::sleep(std::time::Duration::from_secs(2));
}
});
if let Err(error) = watch {
tracing::warn!(%error, "the runtime's background compiles stay on the frames' cores");
}
});
}
fn carve_submit_core_alone() {
use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetProcessAffinityMask, SetProcessDefaultCpuSets};
if submit_core_mode() == SubmitCore::Off || std::env::var_os("EONACAT_XS_SUBMIT_CORE_ALONE").is_none_or(|v| v != "1") {
return;
}
let sets = cpu_sets();
let classes: Vec<(u32, u8)> = sets.iter().map(|s| (s.0, s.1)).collect();
if !fast_of(&classes).is_empty() {
return;
}
let mut cores: Vec<u8> = sets.iter().map(|s| s.3).collect();
cores.sort_unstable();
cores.dedup();
if cores.len() < 6 || sets.len() < cores.len() * 2 {
tracing::info!(cores = cores.len(), logical = sets.len(), "no core kept for the submitting thread: fewer than six cores, or no SMT");
return;
}
let core = *cores.last().expect("six cores or more");
let Some(&(id, ..)) = sets.iter().filter(|s| s.3 == core).min_by_key(|s| s.2) else { return };
let others: Vec<u32> = sets.iter().filter(|s| s.3 != core).map(|s| s.0).collect();
let every = sets.iter().fold(0usize, |m, s| m | 1 << s.2);
let (mut ours, mut all) = (0usize, 0usize);
if unsafe { GetProcessAffinityMask(GetCurrentProcess(), &mut ours, &mut all) } != 0 && ours & every != every {
tracing::warn!(mask = %format!("{ours:#x}"), "the process was started with an affinity mask: no core kept for the submitting thread");
return;
}
if unsafe { SetProcessDefaultCpuSets(GetCurrentProcess(), others.as_ptr(), others.len() as u32) } == 0 {
tracing::warn!(error = %std::io::Error::last_os_error(), "no core kept for the submitting thread: the process's sets were refused");
return;
}
let _ = PROCESS_SETS.set(others);
SUBMIT_SET.store(id, std::sync::atomic::Ordering::Release);
SUBMIT_ALONE.store(true, std::sync::atomic::Ordering::Release);
tracing::info!(core, set = id, "a physical core kept for the submitting thread alone, every other thread off it (EONACAT_XS_SUBMIT_CORE_ALONE=1)");
}
static SUBMIT_ALONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
fn keep_runtime_compiles_off_the_frames_cores() {
use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE, LocalFree};
use windows_sys::Win32::System::Diagnostics::ToolHelp::{
CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next,
};
use windows_sys::Win32::System::Threading::{
GetCurrentProcessId, GetThreadDescription, OpenThread, SetThreadSelectedCpuSets, THREAD_QUERY_LIMITED_INFORMATION,
THREAD_SET_LIMITED_INFORMATION,
};
static MOVED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let Some((_, rest)) = placed() else { return };
let mut moved = 0;
unsafe {
let own = GetCurrentProcessId();
let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if snapshot == INVALID_HANDLE_VALUE {
return;
}
let mut entry = THREADENTRY32 { dwSize: size_of::<THREADENTRY32>() as u32, ..Default::default() };
let mut more = Thread32First(snapshot, &mut entry) != 0;
while more {
let thread = if entry.th32OwnerProcessID == own {
OpenThread(THREAD_QUERY_LIMITED_INFORMATION | THREAD_SET_LIMITED_INFORMATION, 0, entry.th32ThreadID)
} else {
std::ptr::null_mut()
};
if !thread.is_null() {
let mut name = std::ptr::null_mut();
if GetThreadDescription(thread, &mut name) >= 0 && !name.is_null() {
let len = (0..).take_while(|&i| *name.add(i) != 0).count();
let text = String::from_utf16_lossy(std::slice::from_raw_parts(name, len));
LocalFree(name.cast());
if text.starts_with("D3D") && text.to_lowercase().contains("background") {
moved += usize::from(SetThreadSelectedCpuSets(thread, rest.as_ptr(), rest.len() as u32) != 0);
}
}
CloseHandle(thread);
}
more = Thread32Next(snapshot, &mut entry) != 0;
}
CloseHandle(snapshot);
}
if moved > MOVED.swap(moved, std::sync::atomic::Ordering::Relaxed) {
tracing::info!(threads = moved, "the runtime's background compiles run on the half the frames' are not on");
}
}
fn placed() -> Option<&'static (Vec<u32>, Vec<u32>)> {
halves().filter(|_| PLACED.load(std::sync::atomic::Ordering::Relaxed))
}
pub(crate) fn keep_off_the_frames_cores(what: &str) {
use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadSelectedCpuSets};
let Some((_, rest)) = placed() else { return };
if unsafe { SetThreadSelectedCpuSets(GetCurrentThread(), rest.as_ptr(), rest.len() as u32) } == 0 {
tracing::warn!(what, error = %std::io::Error::last_os_error(), "the thread could not be kept off the frames' cores");
}
}
pub(crate) fn hold_long_on_fast_cores() -> bool {
long_from().is_some()
}
fn long_from() -> Option<u8> {
static FROM: std::sync::OnceLock<Option<u8>> = std::sync::OnceLock::new();
*FROM.get_or_init(|| {
let v = std::env::var("EONACAT_XS_PIPELINE_FAST_CORES").ok()?;
v.trim().parse().ok()
})
}
pub(crate) fn hold_on_fast_cores(hold: bool) {
use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadSelectedCpuSets};
static FAST: std::sync::OnceLock<Vec<u32>> = std::sync::OnceLock::new();
let fast = FAST.get_or_init(|| {
let from = long_from().unwrap_or(0);
let mut fast = fast_from(&cpu_sets(), from);
if let Some((_, rest)) = placed() {
fast.retain(|id| rest.contains(id));
}
tracing::info!(fast = fast.len(), from, "long pipelines are kept on the fast cores");
fast
});
if fast.is_empty() {
return;
}
let back = placed().map(|h| &h.1);
let (list, n) = match (hold, back) {
(true, _) => (fast.as_ptr(), fast.len() as u32),
(false, Some(rest)) => (rest.as_ptr(), rest.len() as u32),
(false, None) => (std::ptr::null(), 0),
};
if unsafe { SetThreadSelectedCpuSets(GetCurrentThread(), list, n) } == 0 {
tracing::warn!(hold, error = %std::io::Error::last_os_error(), "the pipeline worker's processors could not be set");
}
}
pub(crate) fn off_the_frames_cores() -> usize {
placed().map_or_else(|| std::thread::available_parallelism().map_or(4, |n| n.get()), |h| h.1.len())
}
fn stage() -> u32 {
static STAGE: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
*STAGE.get_or_init(|| std::env::var("EONACAT_XS_FAST_CORES").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(1))
}
pub(crate) fn keep_submit_core(what: &str) {
use windows_sys::Win32::System::Threading::{
GetCurrentThread, SetThreadPriority, SetThreadSelectedCpuSets, THREAD_PRIORITY_ABOVE_NORMAL,
THREAD_PRIORITY_HIGHEST,
};
keep_on_fast_cores(what);
let prio = match std::env::var("EONACAT_XS_SUBMIT_PRIORITY").ok().and_then(|v| v.trim().parse::<i32>().ok()) {
Some(p) => p.clamp(-2, 2),
None => {
if PLACED.load(std::sync::atomic::Ordering::Acquire) || SUBMIT_ALONE.load(std::sync::atomic::Ordering::Acquire) {
THREAD_PRIORITY_HIGHEST
} else {
THREAD_PRIORITY_ABOVE_NORMAL
}
}
};
unsafe { SetThreadPriority(GetCurrentThread(), prio) };
let id = SUBMIT_SET.load(std::sync::atomic::Ordering::Acquire);
if id != 0 {
let ids = [id];
if unsafe { SetThreadSelectedCpuSets(GetCurrentThread(), ids.as_ptr(), 1) } != 0 {
tracing::info!(what, set = id, priority = prio, "submitting thread placed on dedicated core (EONACAT_XS_SUBMIT_CORE)");
} else {
tracing::warn!(what, error = %std::io::Error::last_os_error(), "could not pin submitting thread to dedicated core");
}
}
}
pub(crate) fn keep_on_fast_cores(what: &str) {
ask(what, 1);
}
pub(crate) fn keep_helper_on_fast_cores(what: &str) {
ask(what, 2);
}
pub(crate) fn keep_many_on_fast_cores(what: &str) {
ask(what, 3);
}
fn list_priority_for(is_placed: bool, override_val: Option<&str>, helper_prio: Option<i32>) -> Option<i32> {
if let Some(p) = override_val.and_then(|v| v.trim().parse::<i32>().ok()) {
return Some(p.clamp(-2, 2));
}
if is_placed {
Some(windows_sys::Win32::System::Threading::THREAD_PRIORITY_BELOW_NORMAL)
} else {
helper_prio
}
}
pub(crate) fn keep_list_worker(what: &str) {
use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority};
select_fast_cores(what, 3);
keep_translators_off_the_cache(what);
let env = std::env::var("EONACAT_XS_LIST_PRIORITY").ok();
let placed_now = PLACED.load(std::sync::atomic::Ordering::Acquire);
if let Some(priority) = list_priority_for(placed_now, env.as_deref(), helper_priority()) {
let set = unsafe { SetThreadPriority(GetCurrentThread(), priority) } != 0;
tracing::debug!(what, priority, set, "list translator priority (EONACAT_XS_LIST_PRIORITY)");
}
}
fn helper_priority() -> Option<i32> {
static PRIORITY: std::sync::OnceLock<Option<i32>> = std::sync::OnceLock::new();
*PRIORITY.get_or_init(|| {
std::env::var("EONACAT_XS_HELPER_PRIORITY").ok().and_then(|v| v.trim().parse::<i32>().ok()).map(|p| p.clamp(-2, 2))
})
}
fn ask(what: &str, from: u32) {
use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority};
if let Some(priority) = helper_priority() {
let set = unsafe { SetThreadPriority(GetCurrentThread(), priority) } != 0;
tracing::debug!(what, priority, set, "the thread's priority (EONACAT_XS_HELPER_PRIORITY)");
}
select_fast_cores(what, from);
}
fn select_fast_cores(what: &str, from: u32) {
use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadSelectedCpuSets};
if stage() < from {
return;
}
static FAST: std::sync::OnceLock<(Vec<u32>, usize)> = std::sync::OnceLock::new();
let (fast, of) = FAST.get_or_init(|| {
let sets = cpu_sets();
let classes: Vec<(u32, u8)> = sets.iter().map(|s| (s.0, s.1)).collect();
(fast_of(&classes), sets.len())
});
if fast.is_empty() {
return;
}
let ok = unsafe { SetThreadSelectedCpuSets(GetCurrentThread(), fast.as_ptr(), fast.len() as u32) };
if ok == 0 {
tracing::warn!(what, error = %std::io::Error::last_os_error(), "the thread could not be kept on the fast cores");
} else {
tracing::info!(what, fast = fast.len(), of, "the thread is kept on the fast cores (EONACAT_XS_FAST_CORES=0: not)");
}
}
fn helpers_raised() -> bool {
crate::toggled!("EONACAT_XS_HELPERS_RAISED")
}
fn raised_priority(on: bool, number: Option<i32>) -> i32 {
use windows_sys::Win32::System::Threading::{THREAD_PRIORITY_ABOVE_NORMAL, THREAD_PRIORITY_NORMAL};
if on { number.unwrap_or(THREAD_PRIORITY_ABOVE_NORMAL) } else { THREAD_PRIORITY_NORMAL }
}
pub(crate) struct Priority {
applied: Option<bool>,
}
impl Priority {
pub(crate) fn new() -> Self {
let mut priority = Self { applied: None };
priority.keep();
priority
}
pub(crate) fn keep(&mut self) {
use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority};
let on = helpers_raised();
if self.applied == Some(on) {
return;
}
let priority = raised_priority(on, helper_priority());
unsafe { SetThreadPriority(GetCurrentThread(), priority) };
self.applied = Some(on);
}
}
pub(crate) mod log {
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, LazyLock, Mutex};
pub(crate) const COPIES: usize = 0;
pub(crate) const HEAP: usize = 1;
const WHAT: [&str; 2] = ["copies", "heap pass"];
const CPUS: usize = 64;
static ON: LazyLock<bool> = LazyLock::new(|| std::env::var_os("EONACAT_XS_CPU_LOG").is_some_and(|v| v == "1"));
struct Thread {
name: String,
micros: [[AtomicU64; CPUS]; 2],
}
static THREADS: Mutex<Vec<Arc<Thread>>> = Mutex::new(Vec::new());
thread_local! {
static THIS: Arc<Thread> = {
let this = Arc::new(Thread {
name: std::thread::current().name().unwrap_or("title").to_owned(),
micros: std::array::from_fn(|_| std::array::from_fn(|_| AtomicU64::new(0))),
});
THREADS.lock().unwrap_or_else(|e| e.into_inner()).push(this.clone());
this
};
}
pub(crate) fn note(what: usize, us: u64) {
if !*ON {
return;
}
static WATCHER: std::sync::Once = std::sync::Once::new();
WATCHER.call_once(|| {
std::thread::Builder::new().name("eonacat-xs-cpu-log".into()).spawn(watch).ok();
});
let cpu = unsafe { windows_sys::Win32::System::Threading::GetCurrentProcessorNumber() } as usize;
THIS.with(|t| t.micros[what][cpu.min(CPUS - 1)].fetch_add(us, Ordering::Relaxed));
}
fn watch() {
let sets = super::cpu_sets();
let best = sets.iter().map(|c| c.1).max().unwrap_or(0);
let fast = |cpu: usize| sets.iter().any(|c| c.2 as usize == cpu && c.1 == best);
loop {
std::thread::sleep(std::time::Duration::from_secs(1));
let threads = THREADS.lock().unwrap_or_else(|e| e.into_inner()).clone();
for (what, name) in WHAT.iter().enumerate() {
let (mut all, mut on_fast) = (0u64, 0u64);
let mut by = std::collections::BTreeMap::<&str, ([u64; CPUS], usize)>::new();
for t in &threads {
let taken: Vec<u64> = t.micros[what].iter().map(|m| m.swap(0, Ordering::Relaxed)).collect();
if taken.iter().all(|&us| us == 0) {
continue;
}
let entry = by.entry(&t.name).or_insert(([0; CPUS], 0));
entry.1 += 1;
for (cpu, &us) in taken.iter().enumerate() {
entry.0[cpu] += us;
all += us;
if fast(cpu) {
on_fast += us;
}
}
}
if all == 0 {
continue;
}
let threads: Vec<String> = by
.iter()
.map(|(name, (cpus, n))| {
let at: Vec<String> = cpus
.iter()
.enumerate()
.filter(|&(_, &us)| us >= 100)
.map(|(cpu, &us)| format!("{cpu}:{:.1}", us as f64 / 1e3))
.collect();
format!("{name} x{n} {:.1} ms [{}]", cpus.iter().sum::<u64>() as f64 / 1e3, at.join(" "))
})
.collect();
tracing::info!(
"cpu {name} {:.1} ms, {:.0}% on the fast cores: {}",
all as f64 / 1e3,
on_fast as f64 * 100.0 / all as f64,
threads.join("; ")
);
}
}
}
}