use std::collections::HashMap;
use std::fmt::Write as _;
use crate::config::DEFAULT_BUSIEST_THREADS;
pub const PLACEMENT_HZ: u32 = 200;
pub const SIMULTANEOUS_US: f64 = 100.0;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Cpu {
pub index: u32,
pub core: u32,
pub class: u8,
}
#[must_use]
#[cfg_attr(not(all(windows, target_arch = "x86_64")), allow(dead_code))]
pub(crate) fn placement_stride(hz: u32) -> u64 {
u64::from(hz.div_ceil(PLACEMENT_HZ).max(1))
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct PlacedThread {
pub name: String,
pub tid: u32,
}
impl PlacedThread {
#[must_use]
pub fn new(name: impl Into<String>, tid: u32) -> Self {
Self {
name: name.into(),
tid,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Reading {
pub thread: usize,
pub cpu: u32,
pub tsc: u64,
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Placement {
pub unavailable: Option<String>,
pub cpus: Vec<Cpu>,
pub threads: Vec<PlacedThread>,
pub readings: Vec<Reading>,
pub tsc_hz: f64,
pub wall: f64,
pub cycles: HashMap<usize, u64>,
pub highlight_threads: Vec<String>,
pub busiest_threads: usize,
pub pending_at_stop: usize,
}
impl Default for Placement {
fn default() -> Self {
Self {
unavailable: None,
cpus: Vec::new(),
threads: Vec::new(),
readings: Vec::new(),
tsc_hz: 0.0,
wall: 0.0,
cycles: HashMap::new(),
highlight_threads: Vec::new(),
busiest_threads: DEFAULT_BUSIEST_THREADS,
pending_at_stop: 0,
}
}
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct ThreadPlacement {
pub role: String,
pub thread: usize,
pub readings: u64,
pub slow_class: u64,
pub cpu_changes: u64,
pub core_changes: u64,
}
#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct PlacementSummary {
pub threads: Vec<ThreadPlacement>,
pub simultaneous: u64,
pub siblings: u64,
pub sibling_pairs: Vec<(String, String, u64)>,
}
impl Placement {
#[must_use]
pub fn label(&self, index: usize) -> String {
let Some(thread) = self.threads.get(index) else {
return "?".to_owned();
};
let same: Vec<usize> = (0..self.threads.len())
.filter(|&other| {
self.threads
.get(other)
.is_some_and(|t| t.name == thread.name)
})
.collect();
if same.len() < 2 {
return thread.name.clone();
}
let ordinal = same.iter().position(|&other| other == index).unwrap_or(0) + 1;
format!("{} #{ordinal} (tid {})", thread.name, thread.tid)
}
fn cpu(&self, index: u32) -> Option<&Cpu> {
self.cpus.iter().find(|cpu| cpu.index == index)
}
fn fastest_class(&self) -> Option<u8> {
self.cpus.iter().map(|cpu| cpu.class).max()
}
fn is_slow(&self, reading: &Reading, fastest: Option<u8>) -> bool {
let class = self.cpu(reading.cpu).map(|cpu| cpu.class);
class.is_some() && class < fastest
}
#[must_use]
pub fn key_threads(&self) -> Vec<(String, usize)> {
let highlight: Vec<String> = self
.highlight_threads
.iter()
.map(|name| name.trim().to_lowercase())
.filter(|name| !name.is_empty())
.collect();
let mut keys: Vec<(String, usize)> = self
.threads
.iter()
.enumerate()
.filter(|(_, thread)| {
let lower = thread.name.to_lowercase();
highlight.iter().any(|wanted| lower.contains(wanted))
})
.map(|(index, _)| ("highlight".to_owned(), index))
.collect();
let mut readings: HashMap<usize, u64> = HashMap::new();
for reading in &self.readings {
let count = readings.entry(reading.thread).or_default();
*count = count.saturating_add(1);
}
let mut busy: Vec<(u64, u64, usize)> = (0..self.threads.len())
.filter(|index| !keys.iter().any(|(_, key)| key == index))
.map(|index| {
let cycles = self.cycles.get(&index).copied().unwrap_or(0);
let count = readings.get(&index).copied().unwrap_or(0);
(cycles, count, index)
})
.filter(|&(cycles, count, _)| cycles > 0 || count > 0)
.collect();
busy.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)).then(a.2.cmp(&b.2)));
for (rank, &(_, _, index)) in busy.iter().take(self.busiest_threads).enumerate() {
keys.push((format!("busy {}", rank + 1), index));
}
keys
}
#[must_use]
pub fn summarize(&self) -> PlacementSummary {
let keys = self.key_threads();
let fastest = self.fastest_class();
let core = |reading: &Reading| self.cpu(reading.cpu).map(|cpu| cpu.core);
let mut summary = PlacementSummary::default();
for (role, thread) in &keys {
let mut own: Vec<&Reading> = self
.readings
.iter()
.filter(|reading| reading.thread == *thread)
.collect();
own.sort_by_key(|reading| reading.tsc);
let mut entry = ThreadPlacement {
role: role.clone(),
thread: *thread,
readings: own.len() as u64,
slow_class: own.iter().filter(|r| self.is_slow(r, fastest)).count() as u64,
cpu_changes: 0,
core_changes: 0,
};
for pair in own.windows(2) {
let [a, b] = pair else { continue };
if a.cpu != b.cpu {
entry.cpu_changes = entry.cpu_changes.saturating_add(1);
if core(a) != core(b) {
entry.core_changes = entry.core_changes.saturating_add(1);
}
}
}
summary.threads.push(entry);
}
if !(self.tsc_hz.is_finite() && self.tsc_hz > 0.0) {
return summary;
}
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
let window = (SIMULTANEOUS_US * self.tsc_hz / 1e6) as u64;
let mut keyed: Vec<&Reading> = self
.readings
.iter()
.filter(|reading| keys.iter().any(|(_, key)| *key == reading.thread))
.collect();
keyed.sort_by_key(|reading| reading.tsc);
let mut pairs: HashMap<(usize, usize), u64> = HashMap::new();
for (at, reading) in keyed.iter().enumerate() {
let near = |other: &&&Reading| other.tsc.abs_diff(reading.tsc) <= window;
let before = keyed.get(..at).unwrap_or_default().iter().rev();
let after = keyed.get(at + 1..).unwrap_or_default().iter();
let mut together = false;
let mut sibling: Option<usize> = None;
for other in before.take_while(near).chain(after.take_while(near)) {
if other.thread == reading.thread {
continue;
}
together = true;
if other.cpu != reading.cpu && core(other).is_some() && core(other) == core(reading)
{
sibling = Some(other.thread);
}
}
if together {
summary.simultaneous = summary.simultaneous.saturating_add(1);
}
if let Some(other) = sibling {
summary.siblings = summary.siblings.saturating_add(1);
let key = (reading.thread.min(other), reading.thread.max(other));
let count = pairs.entry(key).or_default();
*count = count.saturating_add(1);
}
}
let mut pairs: Vec<(String, String, u64)> = pairs
.into_iter()
.map(|((a, b), count)| (self.label(a), self.label(b), count))
.collect();
pairs.sort_by(|a, b| {
b.2.cmp(&a.2)
.then_with(|| a.0.cmp(&b.0))
.then_with(|| a.1.cmp(&b.1))
});
summary.sibling_pairs = pairs;
summary
}
#[must_use]
pub fn report(&self) -> String {
let mut text = String::from("=== placement\n");
if let Some(reason) = &self.unavailable {
let _ = writeln!(text, "no readings: {reason}\n");
return text;
}
let mut classes: Vec<u8> = self.cpus.iter().map(|cpu| cpu.class).collect();
classes.sort_unstable();
classes.dedup();
let cores = |class: Option<u8>| {
let mut cores: Vec<u32> = self
.cpus
.iter()
.filter(|cpu| class.is_none_or(|class| cpu.class == class))
.map(|cpu| cpu.core)
.collect();
cores.sort_unstable();
cores.dedup();
cores.len()
};
let _ = write!(
text,
"{} logical processors on {} cores;",
self.cpus.len(),
cores(None)
);
for class in classes.iter().rev() {
let logical = self.cpus.iter().filter(|cpu| cpu.class == *class).count();
let _ = write!(
text,
" class {class}: {logical} logical on {} cores;",
cores(Some(*class))
);
}
text.push('\n');
if classes.len() < 2 {
text.push_str("one core class: efficiency-core shares do not apply\n");
}
let mut read: Vec<usize> = self.readings.iter().map(|r| r.thread).collect();
read.sort_unstable();
read.dedup();
let _ = writeln!(
text,
"{} readings over {:.1} s ({} threads read, {} pending at stop); changes are between consecutive readings, so they undercount",
self.readings.len(),
self.wall,
read.len(),
self.pending_at_stop,
);
let summary = self.summarize();
let per_second = |count: u64| {
if self.wall > 0.0 {
count as f64 / self.wall
} else {
0.0
}
};
let percent = |part: u64, whole: u64| {
if whole == 0 {
0.0
} else {
part as f64 * 100.0 / whole as f64
}
};
for entry in &summary.threads {
let _ = writeln!(
text,
"{:<10} {:<24} {:>7} readings, {:>5.1}% on slower cores, {:>7.1} processor changes/s, {:>7.1} core changes/s",
entry.role,
self.label(entry.thread),
entry.readings,
percent(entry.slow_class, entry.readings),
per_second(entry.cpu_changes),
per_second(entry.core_changes),
);
}
let key_readings = summary
.threads
.iter()
.fold(0_u64, |sum, entry| sum.saturating_add(entry.readings));
if self.tsc_hz.is_finite() && self.tsc_hz > 0.0 {
let _ = writeln!(
text,
"key threads: {} of {key_readings} readings had another key thread within {SIMULTANEOUS_US} us; {} ({:.1}% of all, {:.1}% of those) on another hyperthread of the same core",
summary.simultaneous,
summary.siblings,
percent(summary.siblings, key_readings),
percent(summary.siblings, summary.simultaneous),
);
for (a, b, count) in summary.sibling_pairs.iter().take(6) {
let _ = writeln!(text, " siblings {a} + {b}: {count}");
}
}
let fastest = self.fastest_class();
let slow = self
.readings
.iter()
.filter(|reading| self.is_slow(reading, fastest))
.count() as u64;
let _ = writeln!(
text,
"all read threads: {:.1}% of readings on slower cores\n",
percent(slow, self.readings.len() as u64)
);
text
}
}
#[must_use]
pub fn parse_cpu_sets(bytes: &[u8]) -> Vec<Cpu> {
let u32_at = |entry: &[u8], at: usize| {
entry
.get(at..at + 4)
.and_then(|b| b.try_into().ok())
.map(u32::from_le_bytes)
};
let mut cpus = Vec::new();
let mut at = 0_usize;
while let Some(entry) = bytes.get(at..).filter(|rest| !rest.is_empty()) {
let Some(size) = u32_at(entry, 0).and_then(|size| usize::try_from(size).ok()) else {
break;
};
if size < 20 || entry.len() < size {
break;
}
let group = entry
.get(12..14)
.and_then(|b| b.try_into().ok())
.map(u16::from_le_bytes);
if let (Some(0), Some(group), Some(&logical), Some(&core), Some(&class)) = (
u32_at(entry, 4),
group,
entry.get(14),
entry.get(15),
entry.get(18),
) {
cpus.push(Cpu {
index: u32::from(group) * 64 + u32::from(logical),
core: (u32::from(group) << 8) | u32::from(core),
class,
});
}
let Some(next) = at.checked_add(size) else {
break;
};
at = next;
}
cpus
}
#[cfg(test)]
mod tests {
use super::*;
fn hybrid() -> Vec<Cpu> {
let cpu = |index, core, class| Cpu { index, core, class };
vec![
cpu(0, 0, 1),
cpu(1, 0, 1),
cpu(2, 1, 1),
cpu(3, 1, 1),
cpu(4, 2, 0),
cpu(5, 3, 0),
]
}
fn threads() -> Vec<PlacedThread> {
["render", "audio", "main", "worker-7", "worker-9", "logger"]
.into_iter()
.zip(100..)
.map(|(name, tid)| PlacedThread::new(name, tid))
.collect()
}
fn reading(thread: usize, cpu: u32, tsc: u64) -> Reading {
Reading { thread, cpu, tsc }
}
#[test]
fn key_threads_are_highlighted_then_busiest() {
let mut placement = Placement {
threads: threads(),
cpus: hybrid(),
highlight_threads: vec!["RENDER".into(), "aud".into()],
busiest_threads: 2,
..Placement::default()
};
placement.cycles.insert(3, 500);
placement.cycles.insert(4, 900);
placement.cycles.insert(2, 10);
placement.cycles.insert(0, 10_000);
let keys = placement.key_threads();
assert_eq!(
keys,
vec![
("highlight".to_owned(), 0),
("highlight".to_owned(), 1),
("busy 1".to_owned(), 4),
("busy 2".to_owned(), 3),
]
);
}
#[test]
fn busiest_ties_break_by_readings_then_index() {
let mut placement = Placement {
threads: threads(),
busiest_threads: 10,
..Placement::default()
};
placement.cycles.insert(5, 7);
placement.cycles.insert(2, 7);
placement.readings = vec![reading(2, 0, 1), reading(1, 0, 2), reading(1, 0, 3)];
let keys = placement.key_threads();
let indexes: Vec<usize> = keys.iter().map(|(_, index)| *index).collect();
assert_eq!(indexes, vec![2, 5, 1]);
placement.busiest_threads = 0;
assert_eq!(placement.key_threads(), []);
}
#[test]
fn no_highlight_and_no_activity_gives_no_keys() {
assert_eq!(Placement::default().key_threads(), []);
assert_eq!(Placement::default().key_threads(), []);
}
#[test]
fn shares_changes_and_siblings() {
let placement = Placement {
threads: threads(),
cpus: hybrid(),
readings: vec![
reading(0, 0, 1_000_000),
reading(0, 1, 2_000_000),
reading(0, 4, 3_000_000),
reading(1, 1, 1_010_000),
reading(1, 2, 9_000_000),
],
tsc_hz: 1e9,
wall: 2.0,
highlight_threads: vec!["render".into(), "audio".into()],
..Placement::default()
};
let summary = placement.summarize();
assert_eq!(summary.threads.len(), 2);
let render = &summary.threads[0];
assert_eq!((render.readings, render.slow_class), (3, 1));
assert_eq!((render.cpu_changes, render.core_changes), (2, 1));
let audio = &summary.threads[1];
assert_eq!(
(audio.readings, audio.slow_class, audio.core_changes),
(2, 0, 1)
);
assert_eq!(summary.simultaneous, 2);
assert_eq!(summary.siblings, 2);
assert_eq!(
summary.sibling_pairs,
vec![("render".to_owned(), "audio".to_owned(), 2)]
);
let text = placement.report();
assert!(text.contains("6 logical processors on 4 cores"), "{text}");
assert!(text.contains("class 1: 4 logical on 2 cores"), "{text}");
assert!(text.contains("class 0: 2 logical on 2 cores"), "{text}");
assert!(text.contains("siblings render + audio: 2"), "{text}");
assert!(
text.contains("all read threads: 20.0% of readings on slower cores"),
"{text}"
);
assert!(text.contains("1.0 processor changes/s"), "{text}");
}
#[test]
fn simultaneity_window_boundary() {
let base = Placement {
threads: threads(),
cpus: hybrid(),
tsc_hz: 1e9,
wall: 1.0,
highlight_threads: vec!["render".into(), "audio".into()],
..Placement::default()
};
let mut at_edge = base.clone();
at_edge.readings = vec![reading(0, 0, 0), reading(1, 1, 100_000)];
assert_eq!(at_edge.summarize().siblings, 2);
let mut past = base.clone();
past.readings = vec![reading(0, 0, 0), reading(1, 1, 100_001)];
assert_eq!(past.summarize().simultaneous, 0);
let mut same = base.clone();
same.readings = vec![reading(0, 0, 0), reading(1, 0, 10)];
let summary = same.summarize();
assert_eq!((summary.simultaneous, summary.siblings), (2, 0));
let mut apart = base;
apart.readings = vec![reading(0, 0, 0), reading(1, 2, 10)];
let summary = apart.summarize();
assert_eq!((summary.simultaneous, summary.siblings), (2, 0));
}
#[test]
fn a_thread_alone_is_never_simultaneous_with_itself() {
let placement = Placement {
threads: threads(),
cpus: hybrid(),
tsc_hz: 1e9,
readings: vec![reading(0, 0, 0), reading(0, 1, 1)],
highlight_threads: vec!["render".into()],
..Placement::default()
};
let summary = placement.summarize();
assert_eq!((summary.simultaneous, summary.siblings), (0, 0));
}
#[test]
fn unknown_counter_rate_skips_co_scheduling() {
let placement = Placement {
threads: threads(),
cpus: hybrid(),
readings: vec![reading(0, 0, 0), reading(1, 1, 1)],
tsc_hz: f64::NAN,
highlight_threads: vec!["render".into(), "audio".into()],
..Placement::default()
};
let summary = placement.summarize();
assert_eq!(summary.simultaneous, 0);
let text = placement.report();
assert!(!text.contains("key threads:"), "{text}");
assert!(!text.contains("NaN"), "{text}");
}
#[test]
fn readings_on_unknown_processors_are_not_slow() {
let placement = Placement {
threads: threads(),
cpus: hybrid(),
readings: vec![reading(0, 63, 0), reading(0, 4, 1)],
highlight_threads: vec!["render".into()],
..Placement::default()
};
let summary = placement.summarize();
assert_eq!(summary.threads[0].slow_class, 1);
assert_eq!(summary.threads[0].core_changes, 1);
}
#[test]
fn one_core_class_says_so() {
let placement = Placement {
threads: threads(),
cpus: vec![Cpu {
index: 0,
core: 0,
class: 0,
}],
..Placement::default()
};
let text = placement.report();
assert!(text.contains("one core class"), "{text}");
assert!(text.contains("0.0% of readings on slower cores"), "{text}");
}
#[test]
fn same_named_threads_stay_apart() {
let cpu = |index, core| Cpu {
index,
core,
class: 1,
};
let cpus = vec![cpu(0, 0), cpu(1, 0), cpu(2, 1), cpu(3, 1)];
let placement = Placement {
cpus,
threads: vec![
PlacedThread::new("worker", 10),
PlacedThread::new("worker", 11),
],
readings: vec![
reading(0, 0, 1_000),
reading(1, 1, 1_010),
reading(0, 0, 2_000_000),
reading(1, 1, 2_000_010),
reading(0, 0, 4_000_000),
reading(1, 2, 4_000_010),
],
tsc_hz: 1e9,
wall: 1.0,
highlight_threads: vec!["worker".into()],
..Placement::default()
};
let summary = placement.summarize();
assert_eq!(summary.threads.len(), 2);
assert_eq!(summary.threads[0].cpu_changes, 0, "no fake migration");
assert_eq!(summary.threads[1].cpu_changes, 1);
assert_eq!(summary.threads[1].core_changes, 1);
assert_eq!(summary.simultaneous, 6);
assert_eq!(summary.siblings, 4);
assert_eq!(
summary.sibling_pairs,
vec![(
"worker #1 (tid 10)".to_owned(),
"worker #2 (tid 11)".to_owned(),
4
)]
);
let text = placement.report();
assert!(text.contains("worker #1 (tid 10)"), "{text}");
assert!(text.contains("worker #2 (tid 11)"), "{text}");
assert_eq!(
Placement {
threads: threads(),
..Placement::default()
}
.label(0),
"render"
);
assert_eq!(Placement::default().label(3), "?");
}
#[test]
fn the_placement_rate_stays_under_its_ceiling() {
for hz in [1, 100, 199, 200, 201, 399, 400, 401, 1000, 1999, 2000] {
let stride = placement_stride(hz);
assert!(
f64::from(hz) / stride as f64 <= f64::from(PLACEMENT_HZ),
"{hz} Hz every {stride} passes"
);
}
assert_eq!(placement_stride(399), 2);
assert_eq!(placement_stride(200), 1);
assert_eq!(placement_stride(0), 1);
}
#[test]
fn huge_counts_saturate() {
let mut placement = Placement {
threads: threads(),
busiest_threads: 1,
..Placement::default()
};
placement.cycles.insert(0, u64::MAX);
assert_eq!(placement.key_threads(), vec![("busy 1".to_owned(), 0)]);
}
#[test]
fn unavailable_reason_is_reported() {
let placement = Placement {
threads: threads(),
unavailable: Some("QueueUserAPC2 is missing".into()),
..Placement::default()
};
assert!(
placement
.report()
.contains("no readings: QueueUserAPC2 is missing")
);
}
fn entry(kind: u32, group: u16, logical: u8, core: u8, class: u8, size: u32) -> Vec<u8> {
let mut bytes = vec![0_u8; size.max(20) as usize];
bytes[0..4].copy_from_slice(&size.to_le_bytes());
bytes[4..8].copy_from_slice(&kind.to_le_bytes());
bytes[12..14].copy_from_slice(&group.to_le_bytes());
bytes[14] = logical;
bytes[15] = core;
bytes[18] = class;
bytes
}
#[test]
fn cpu_set_entries_parse() {
let mut bytes = entry(0, 0, 0, 0, 1, 32);
bytes.extend(entry(0, 0, 1, 0, 1, 32));
bytes.extend(entry(7, 0, 2, 1, 1, 32));
bytes.extend(entry(0, 1, 3, 5, 0, 32));
bytes.extend([1, 2, 3]);
let cpu = |index, core, class| Cpu { index, core, class };
assert_eq!(
parse_cpu_sets(&bytes),
vec![cpu(0, 0, 1), cpu(1, 0, 1), cpu(67, (1 << 8) | 5, 0)]
);
}
#[test]
fn cpu_set_malformed_entries_stop_the_walk() {
assert_eq!(parse_cpu_sets(&[]), []);
let mut zero = entry(0, 0, 0, 0, 1, 32);
zero[0..4].copy_from_slice(&0_u32.to_le_bytes());
assert_eq!(parse_cpu_sets(&zero), []);
assert_eq!(parse_cpu_sets(&entry(0, 0, 0, 0, 1, 19)[..19]), []);
let mut long = entry(0, 0, 0, 0, 1, 32);
long[0..4].copy_from_slice(&64_u32.to_le_bytes());
assert_eq!(parse_cpu_sets(&long), []);
assert_eq!(parse_cpu_sets(&entry(0, 2, 9, 4, 3, 20)).len(), 1);
let mut huge = entry(0, 0, 0, 0, 1, 32);
huge[0..4].copy_from_slice(&u32::MAX.to_le_bytes());
assert_eq!(parse_cpu_sets(&huge), []);
}
}