metric.rs
This file
Path
src/metric.rs
505 lines · 16.8 KiB · Rust
Last changed by
Alternative performance metrics in the terminal (#986)David Peterbefore adoptionbdbfae9
History of this fileTake it
Alternative performance metrics in the terminal (#986)David Peterbefore adoptionbdbfae9
lines 1–505why, one step back1//! Metric selection, descriptive statistics, and display units.23use anyhow::{bail, ensure, Result};45use crate::benchmark::measurement::{Measurement, Measurements};6use crate::quantity::statistics::{max, mean, median, min, standard_deviation};7use crate::quantity::{byte, ratio, second, Ratio};89#[derive(Debug, Clone, Copy, PartialEq, Eq)]10pub enum Metric {11 TimeWallClock,12 TimeCpu,13 TimeUser,14 TimeSystem,15 MemoryPeakResident,16 CpuCycles,17 Instructions,18 CacheReferences,19 CacheMisses,20 BranchMisses,21}2223impl Metric {24 pub const ALL: [Self; 10] = [25 Self::TimeWallClock,26 Self::TimeCpu,27 Self::TimeUser,28 Self::TimeSystem,29 Self::MemoryPeakResident,30 Self::CpuCycles,31 Self::Instructions,32 Self::CacheReferences,33 Self::CacheMisses,34 Self::BranchMisses,35 ];3637 pub fn name(self) -> &'static str {38 match self {39 Self::TimeWallClock => "time_wall_clock",40 Self::TimeCpu => "time_cpu",41 Self::TimeUser => "time_user",42 Self::TimeSystem => "time_system",43 Self::MemoryPeakResident => "memory_peak_resident",44 Self::CpuCycles => "cpu_cycles",45 Self::Instructions => "instructions",46 Self::CacheReferences => "cache_references",47 Self::CacheMisses => "cache_misses",48 Self::BranchMisses => "branch_misses",49 }50 }5152 pub fn label(self) -> &'static str {53 match self {54 Self::TimeWallClock => "Wall Time",55 Self::TimeCpu => "CPU time",56 Self::TimeUser => "User time",57 Self::TimeSystem => "System time",58 Self::MemoryPeakResident => "Memory",59 Self::CpuCycles => "CPU cycles",60 Self::Instructions => "Instructions",61 Self::CacheReferences => "Cache references",62 Self::CacheMisses => "Cache misses",63 Self::BranchMisses => "Branch misses",64 }65 }6667 /// Extract a value in canonical units: seconds, bytes, or counts.68 pub fn value(self, measurement: &Measurement) -> Option<f64> {69 let counters = &measurement.hardware_counters;70 match self {71 Self::TimeWallClock => Some(measurement.time_wall_clock.get::<second>()),72 Self::TimeCpu => Some(measurement.time_cpu.get::<second>()),73 Self::TimeUser => Some(measurement.time_user.get::<second>()),74 Self::TimeSystem => Some(measurement.time_system.get::<second>()),75 Self::MemoryPeakResident => measurement.memory_peak_resident.map(|v| v.get::<byte>()),76 Self::CpuCycles => counters.cpu_cycles.map(|v| v as f64),77 Self::Instructions => counters.instructions.map(|v| v as f64),78 Self::CacheReferences => counters.cache_references.map(|v| v as f64),79 Self::CacheMisses => counters.cache_misses.map(|v| v as f64),80 Self::BranchMisses => counters.branch_misses.map(|v| v as f64),81 }82 }8384 pub fn is_time(self) -> bool {85 matches!(86 self,87 Self::TimeWallClock | Self::TimeCpu | Self::TimeUser | Self::TimeSystem88 )89 }9091 pub fn is_counter(self) -> bool {92 !self.is_time() && self != Self::MemoryPeakResident93 }9495 /// Reject known unsupported configurations before any commands execute.96 /// Availability that depends on permissions or hardware is checked after collection.97 pub fn ensure_available(self, shell: bool) -> Result<()> {98 if self.is_counter() {99 ensure!(100 !shell,101 "Metric '{}' is unavailable when a shell is enabled",102 self.name()103 );104 ensure!(105 cfg!(any(106 target_os = "macos",107 all(108 target_os = "linux",109 target_pointer_width = "64",110 any(111 target_arch = "aarch64",112 target_arch = "x86_64",113 target_arch = "riscv64",114 target_arch = "powerpc64",115 target_arch = "loongarch64"116 )117 )118 )),119 "Metric '{}' is unavailable on this platform",120 self.name()121 );122 ensure!(123 !cfg!(target_os = "macos") || matches!(self, Self::CpuCycles | Self::Instructions),124 "Metric '{}' is unavailable on macOS",125 self.name()126 );127 }128 ensure!(129 !cfg!(windows) || self != Self::MemoryPeakResident,130 "Metric '{}' is unavailable on Windows",131 self.name()132 );133 Ok(())134 }135136 pub fn base_unit(self) -> Unit {137 if self.is_time() {138 Unit::new("s", 1.0)139 } else if self.is_counter() {140 Unit::new("count", 1.0)141 } else {142 Unit::new("B", 1.0)143 }144 }145146 fn units(self) -> &'static [Unit] {147 if self.is_time() {148 TIME_UNITS149 } else if self.is_counter() {150 COUNT_UNITS151 } else {152 MEMORY_UNITS153 }154 }155156 /// Require complete coverage so different metrics describe the same runs.157 pub fn summarize(self, measurements: &Measurements) -> Option<Stats> {158 let values = measurements159 .measurements160 .iter()161 .map(|measurement| self.value(measurement))162 .collect::<Option<Vec<_>>>()?;163 if values.is_empty() {164 return None;165 }166 Some(Stats {167 count: values.len(),168 mean: mean(values.iter().copied()),169 stddev: (values.len() > 1).then(|| {170 standard_deviation(values.iter().map(|&v| Ratio::new::<ratio>(v))).get::<ratio>()171 }),172 median: median(values.iter().copied()),173 min: min(values.iter().copied()),174 max: max(values.iter().copied()),175 })176 }177}178179#[derive(Debug, Clone, Copy, PartialEq)]180pub struct MetricSelection {181 pub metric: Metric,182 pub unit: Option<Unit>,183}184185impl Default for MetricSelection {186 fn default() -> Self {187 Self {188 metric: Metric::TimeWallClock,189 unit: None,190 }191 }192}193194impl MetricSelection {195 /// Parse an ordered, nonempty list of `METRIC[:UNIT]` selections.196 pub fn parse_list(input: &str) -> Result<Vec<Self>> {197 let mut selections = Vec::new();198 for item in input.split(',') {199 let (name, unit_name) = match item.split_once(':') {200 Some((name, unit)) => (name, Some(unit)),201 None => (item, None),202 };203 let metric = match Metric::ALL.iter().copied().find(|m| m.name() == name) {204 Some(metric) => metric,205 None => bail!(206 "Unknown metric '{name}'. Expected one of: {}",207 Metric::ALL.map(Metric::name).join(", ")208 ),209 };210 if selections211 .iter()212 .any(|selection: &Self| selection.metric == metric)213 {214 bail!("Metric '{name}' was selected more than once");215 }216 let unit = match unit_name {217 None => None,218 Some(unit_name) => {219 // Accept an ASCII spelling for microseconds as well.220 let unit_name = if unit_name == "us" { "µs" } else { unit_name };221 match metric.units().iter().find(|unit| unit.symbol == unit_name) {222 Some(unit) => Some(*unit),223 None => bail!(224 "Unit '{unit_name}' is not valid for metric '{name}'. Expected one of: {}",225 metric.units().iter().map(|u| u.symbol).collect::<Vec<_>>().join(", ")226 ),227 }228 }229 };230 selections.push(Self { metric, unit });231 }232 Ok(selections)233 }234235 pub fn display_unit(self, mean: f64) -> Unit {236 if let Some(unit) = self.unit {237 return unit;238 }239 if mean == 0.0 {240 return self.metric.base_unit();241 }242 let units = if self.metric == Metric::MemoryPeakResident {243 BINARY_MEMORY_UNITS244 } else {245 self.metric.units()246 };247 units248 .iter()249 .rev()250 .find(|unit| mean.abs() >= unit.scale)251 .copied()252 .unwrap_or(units[0])253 }254255 /// CSV never automatically scales values.256 pub fn csv_unit(self) -> Unit {257 self.unit.unwrap_or_else(|| self.metric.base_unit())258 }259}260261#[derive(Debug, Clone, Copy, PartialEq)]262pub struct Unit {263 pub symbol: &'static str,264 /// The number of canonical units in this unit (e.g. 1e9 for a billion).265 pub scale: f64,266}267268impl Unit {269 const fn new(symbol: &'static str, scale: f64) -> Self {270 Self { symbol, scale }271 }272273 pub fn format(self, value: f64) -> String {274 let value = self.format_value(value);275 if self.symbol == "count" {276 value277 } else {278 format!("{value} {}", self.symbol)279 }280 }281282 pub fn format_value(self, value: f64) -> String {283 let precision = if self.symbol == "s" { 3 } else { 1 };284 format!("{:.precision$}", value / self.scale)285 }286}287288const TIME_UNITS: &[Unit] = &[289 Unit::new("ns", 1e-9),290 Unit::new("µs", 1e-6),291 Unit::new("ms", 1e-3),292 Unit::new("s", 1.0),293 Unit::new("min", 60.0),294 Unit::new("h", 3600.0),295];296297const BINARY_MEMORY_UNITS: &[Unit] = &[298 Unit::new("B", 1.0),299 Unit::new("KiB", 1024.0),300 Unit::new("MiB", 1_048_576.0),301 Unit::new("GiB", 1_073_741_824.0),302 Unit::new("TiB", 1_099_511_627_776.0),303];304305const MEMORY_UNITS: &[Unit] = &[306 Unit::new("B", 1.0),307 Unit::new("kB", 1e3),308 Unit::new("MB", 1e6),309 Unit::new("GB", 1e9),310 Unit::new("TB", 1e12),311 Unit::new("KiB", 1024.0),312 Unit::new("MiB", 1_048_576.0),313 Unit::new("GiB", 1_073_741_824.0),314 Unit::new("TiB", 1_099_511_627_776.0),315];316317const COUNT_UNITS: &[Unit] = &[318 Unit::new("count", 1.0),319 Unit::new("k", 1e3),320 Unit::new("M", 1e6),321 Unit::new("B", 1e9),322];323324#[derive(Debug, Clone, Copy)]325pub struct Stats {326 pub count: usize,327 pub mean: f64,328 pub stddev: Option<f64>,329 pub median: f64,330 pub min: f64,331 pub max: f64,332}333334impl Stats {335 pub fn change_from(&self, reference: &Self) -> Option<f64> {336 (reference.mean != 0.0).then(|| 100.0 * (self.mean / reference.mean - 1.0))337 }338339 pub fn format_change_from(&self, reference: &Self) -> String {340 let Some(change) = self.change_from(reference) else {341 return "N/A".to_owned();342 };343 let mut formatted = format!("{change:+.1}%");344 if formatted == "+0.0%" || formatted == "-0.0%" {345 formatted = "0.0%".to_owned();346 }347 formatted348 }349350 pub fn format_factor_from(&self, reference: &Self, metric: Metric) -> String {351 if reference.mean > 0.0352 && (self.mean >= 1.3 * reference.mean || self.mean <= 0.7 * reference.mean)353 {354 let decrease = self.mean < reference.mean;355 let factor = if decrease {356 reference.mean / self.mean357 } else {358 self.mean / reference.mean359 };360 let direction = match (metric.is_time(), decrease) {361 (true, true) => "faster",362 (true, false) => "slower",363 (false, true) => "less",364 (false, false) => "more",365 };366 let factor = if factor.is_infinite() {367 "∞".to_owned()368 } else {369 format!("{factor:.1}")370 };371 format!("({factor}x {direction})")372 } else {373 String::new()374 }375 }376}377378#[cfg(test)]379mod tests {380 use super::*;381 use crate::quantity::{Information, Time};382383 #[test]384 fn large_changes_include_factors() {385 let reference = Stats {386 count: 1,387 mean: 100.0,388 stddev: None,389 median: 100.0,390 min: 100.0,391 max: 100.0,392 };393 for (mean, metric, expected) in [394 (130.0, Metric::TimeWallClock, "+30.0% (1.3x slower)"),395 (70.0, Metric::TimeCpu, "-30.0% (1.4x faster)"),396 (10.0, Metric::Instructions, "-90.0% (10.0x less)"),397 (1000.0, Metric::MemoryPeakResident, "+900.0% (10.0x more)"),398 (129.99, Metric::TimeWallClock, "+30.0%"),399 (70.01, Metric::Instructions, "-30.0%"),400 (100.0, Metric::Instructions, "0.0%"),401 (0.0, Metric::Instructions, "-100.0% (∞x less)"),402 ] {403 let stats = Stats { mean, ..reference };404 let (percentage, factor) = expected405 .split_once(" (")406 .map_or((expected, String::new()), |(p, f)| (p, format!("({f}")));407 assert_eq!(stats.format_change_from(&reference), percentage);408 assert_eq!(stats.format_factor_from(&reference, metric), factor);409 }410 let zero = Stats {411 mean: 0.0,412 ..reference413 };414 assert_eq!(reference.format_change_from(&zero), "N/A");415 }416417 #[test]418 fn cpu_time_statistics_use_per_run_totals() {419 let measurements = Measurements::new(420 [(1.0, 3.0), (3.0, 1.0)]421 .iter()422 .map(|&(user, system)| Measurement {423 time_cpu: Time::new::<second>(user + system),424 time_user: Time::new::<second>(user),425 time_system: Time::new::<second>(system),426 ..Measurement::default()427 })428 .collect(),429 );430 let selection = MetricSelection::parse_list("time_cpu:ms").unwrap()[0];431 let stats = selection.metric.summarize(&measurements).unwrap();432 assert_eq!(selection.csv_unit().format(stats.mean), "4000.0 ms");433 // User and system time vary, but their per-run total is constant.434 assert_eq!(stats.stddev, Some(0.0));435 assert_eq!(stats.min, 4.0);436 assert_eq!(stats.max, 4.0);437 let json = serde_json::to_value(&measurements).unwrap();438 for sample in json["measurements"].as_array().unwrap() {439 assert_eq!(sample["time_cpu"]["value"], 4.0);440 assert_eq!(sample["time_cpu"]["unit"], "second");441 }442 }443444 #[test]445 fn selection_units_and_validation() {446 let selections = MetricSelection::parse_list(447 "instructions:B,memory_peak_resident:B,time_wall_clock:ms,time_user:us",448 )449 .unwrap();450 assert_eq!(selections[0].csv_unit().scale, 1e9);451 assert_eq!(selections[1].csv_unit().scale, 1.0);452 assert_eq!(selections[2].csv_unit().format(0.125), "125.0 ms");453 assert_eq!(selections[3].csv_unit().symbol, "µs");454455 let instructions = MetricSelection::parse_list("instructions").unwrap()[0];456 assert_eq!(instructions.csv_unit().symbol, "count");457 assert_eq!(458 instructions.display_unit(143.2e9).format(143.2e9),459 "143.2 B"460 );461 for invalid in [462 "",463 "unknown",464 "time_wall_clock,",465 "instructions,instructions:M",466 "instructions:MiB",467 "memory_peak_resident:ms",468 "time_wall_clock:",469 ] {470 assert!(MetricSelection::parse_list(invalid).is_err(), "{}", invalid);471 }472 }473474 #[test]475 fn summaries_require_complete_samples() {476 let mut measurements = Measurements::new(vec![Measurement {477 memory_peak_resident: Some(Information::new::<byte>(10.0)),478 ..Measurement::default()479 }]);480 let single = Metric::MemoryPeakResident.summarize(&measurements).unwrap();481 assert_eq!(single.stddev, None);482 measurements.push(Measurement::default());483 assert!(Metric::MemoryPeakResident484 .summarize(&measurements)485 .is_none());486 measurements.measurements[1].memory_peak_resident = Some(Information::new::<byte>(30.0));487 let stats = Metric::MemoryPeakResident.summarize(&measurements).unwrap();488 assert_eq!(stats.mean, 20.0);489 assert_eq!(stats.change_from(&single), Some(100.0));490 assert_eq!(stats.format_change_from(&single), "+100.0%");491 assert_eq!(single.format_change_from(&stats), "-50.0%");492 assert_eq!(493 Stats {494 mean: 9.999,495 ..single496 }497 .format_change_from(&single),498 "0.0%"499 );500 approx::assert_relative_eq!(stats.stddev.unwrap(), 200.0_f64.sqrt());501 let zero = Metric::TimeWallClock.summarize(&measurements).unwrap();502 assert_eq!(zero.change_from(&zero), None);503 assert_eq!(zero.format_change_from(&zero), "N/A");504 }505}