From c84dd7b0390c0e64d967dfdc29487e0ad83ac46b Mon Sep 17 00:00:00 2001 From: fargito Date: Tue, 17 Nov 2026 15:17:09 +0000 Subject: [PATCH] feat: report walltime percentiles and rounds Walltime benchmarks run many rounds, but the results only carried summary stats. Report the distribution as well: - Each benchmark's stats gain `percentiles_ns`, p1 to p99 of the time per iteration. They use statrs' quantile formula on the rounds sorted once: statrs runs an O(n) selection per call, so 99 calls took 5.2 s on 10M rounds against 0.38 s for one sort. q1, median and q3 now come from them: q1 and q3 are unchanged, and the median, mean and stdev can differ in the last floating-point bit. - cargo-codspeed writes the time and iteration count of every round, in execution order, to `walltime_rounds/.json.gz` next to `results/.json`. Above 100,000 rounds, a benchmark keeps a uniformly random subsample, still in execution order, and then has fewer rounds than `stats.rounds`: on a 9.7M-round benchmark, that subsample kept p1 to p99 within 1.5% and the CDF within 0.4%. The runner uploads walltime profile folders uncompressed, so the file is gzipped, at the fastest level: it runs 11 times faster than the default on 2.5M rounds, for a file 20 to 30% larger. The per-benchmark files under `target/codspeed/walltime/raw_results/` now carry the rounds until cargo-codspeed aggregates them, so they are written as compact JSON and read through a buffer. Results files keep parsing with older consumers: the new stats field is optional, and the rounds live in their own file. Refs COD-4241 --- Cargo.lock | 49 +++++ crates/cargo-codspeed/Cargo.toml | 1 + crates/cargo-codspeed/src/run.rs | 37 ++-- crates/codspeed/src/walltime_results.rs | 236 ++++++++++++++++++++++-- 4 files changed, 299 insertions(+), 24 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4660ca45..4cc2503e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 3 +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + [[package]] name = "aho-corasick" version = "1.1.3" @@ -377,6 +383,7 @@ dependencies = [ "cargo_metadata", "clap", "codspeed", + "flate2", "fs_extra", "itertools 0.14.0", "predicates", @@ -674,6 +681,15 @@ version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf0a07a401f374238ab8e2f11a104d2851bf9ce711ec69804834de8af45c7af" +[[package]] +name = "crc32fast" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +dependencies = [ + "cfg-if", +] + [[package]] name = "criterion-plot" version = "0.5.0" @@ -831,6 +847,17 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + [[package]] name = "float-cmp" version = "0.9.0" @@ -1420,6 +1447,16 @@ dependencies = [ "libmimalloc-sys", ] +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + [[package]] name = "mio" version = "1.1.1" @@ -2084,6 +2121,12 @@ dependencies = [ "libc", ] +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + [[package]] name = "slab" version = "0.4.9" @@ -2942,3 +2985,9 @@ dependencies = [ "quote", "syn 2.0.96", ] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" diff --git a/crates/cargo-codspeed/Cargo.toml b/crates/cargo-codspeed/Cargo.toml index 007e6df1..9c0e9572 100644 --- a/crates/cargo-codspeed/Cargo.toml +++ b/crates/cargo-codspeed/Cargo.toml @@ -27,6 +27,7 @@ itertools = { workspace = true } anstyle = "1.0.8" serde = { workspace = true } serde_json = { workspace = true } +flate2 = "1.1" toml = "0.8" codspeed = { path = "../codspeed", version = "=6.1.0" } diff --git a/crates/cargo-codspeed/src/run.rs b/crates/cargo-codspeed/src/run.rs index 44ec6d63..fab7fd16 100644 --- a/crates/cargo-codspeed/src/run.rs +++ b/crates/cargo-codspeed/src/run.rs @@ -7,8 +7,9 @@ use crate::{ use anyhow::Context; use cargo_metadata::{Metadata, Package}; use codspeed::walltime_results::WalltimeResults; +use flate2::{write::GzEncoder, Compression}; use std::{ - io::{self, Write}, + io, path::{Path, PathBuf}, }; @@ -172,7 +173,7 @@ pub fn run_benches( } fn aggregate_raw_walltime_data(workspace_root: &Path) -> Result<()> { - let results = WalltimeResults::collect_walltime_results(workspace_root) + let mut results = WalltimeResults::collect_walltime_results(workspace_root) .with_context(|| { format!( "Failed to collect walltime results. This may be due to version incompatibility. \ @@ -196,18 +197,32 @@ fn aggregate_raw_walltime_data(workspace_root: &Path) -> Result<()> { } } - let results_folder = std::env::var("CODSPEED_PROFILE_FOLDER") + let profile_folder = std::env::var("CODSPEED_PROFILE_FOLDER") .map(PathBuf::from) - .unwrap_or_else(|_| workspace_root.join("target/codspeed/profiles")) - .join("results"); + .unwrap_or_else(|_| workspace_root.join("target/codspeed/profiles")); + let results_folder = profile_folder.join("results"); std::fs::create_dir_all(&results_folder).context("Failed to create results folder")?; + let walltime_rounds = results.take_walltime_rounds(); let results_path = results_folder.join(format!("{}.json", std::process::id())); - let mut results_file = - std::fs::File::create(&results_path).context("Failed to create results file")?; - serde_json::to_writer_pretty(&results_file, &results)?; - results_file - .flush() - .context("Failed to flush results file")?; + std::fs::write(&results_path, serde_json::to_vec_pretty(&results)?) + .context("Failed to write results file")?; + + if let Some(walltime_rounds) = walltime_rounds { + let rounds_folder = profile_folder.join("walltime_rounds"); + std::fs::create_dir_all(&rounds_folder).context("Failed to create rounds folder")?; + let rounds_file = + std::fs::File::create(rounds_folder.join(format!("{}.json.gz", std::process::id()))) + .context("Failed to create rounds file")?; + let mut rounds_writer = + io::BufWriter::new(GzEncoder::new(rounds_file, Compression::fast())); + serde_json::to_writer(&mut rounds_writer, &walltime_rounds) + .context("Failed to write rounds file")?; + rounds_writer + .into_inner() + .map_err(io::IntoInnerError::into_error) + .and_then(GzEncoder::finish) + .context("Failed to finish rounds file")?; + } Ok(()) } diff --git a/crates/codspeed/src/walltime_results.rs b/crates/codspeed/src/walltime_results.rs index dc67de84..2d923065 100644 --- a/crates/codspeed/src/walltime_results.rs +++ b/crates/codspeed/src/walltime_results.rs @@ -1,16 +1,21 @@ use anyhow::{Context, Result}; use std::{ - io::Write, + collections::BTreeSet, + io::{BufReader, Write}, path::{Path, PathBuf}, }; use serde::{Deserialize, Serialize}; -use statrs::statistics::{Data, Distribution, Max, Min, OrderStatistics}; +use statrs::statistics::{Data, Distribution, Max, Min}; use crate::utils::generate_unique_id; +// TODO(COD-4241): go-runner in codspeed-go copies this file's percentile and round sampling code; +// make it call this crate instead. const IQR_OUTLIER_FACTOR: f64 = 1.5; const STDEV_OUTLIER_FACTOR: f64 = 3.0; +/// Above this, the rounds file keeps a uniformly random subsample of the rounds, in execution order. +const MAX_WALLTIME_ROUNDS_PER_BENCHMARK: usize = 100_000; #[derive(Debug, Serialize, Deserialize)] pub struct BenchmarkMetadata { @@ -28,6 +33,9 @@ struct BenchmarkStats { q1_ns: f64, median_ns: f64, q3_ns: f64, + /// p1..p99 of the time per iteration + #[serde(default, skip_serializing_if = "Option::is_none")] + percentiles_ns: Option>, rounds: u64, total_time: f64, @@ -45,6 +53,25 @@ struct BenchmarkConfig { max_rounds: Option, } +#[derive(Debug, Serialize, Deserialize)] +struct BenchmarkRounds { + times_per_round_ns: Vec, + iters_per_round: Vec, +} + +#[derive(Debug, Serialize)] +struct UriRounds { + uri: String, + #[serde(flatten)] + rounds: BenchmarkRounds, +} + +/// Content of `walltime_rounds/.json.gz` in the profile folder +#[derive(Debug, Serialize)] +pub struct WalltimeRounds { + benchmarks: Vec, +} + #[derive(Debug, Serialize, Deserialize)] pub struct WalltimeBenchmark { #[serde(flatten)] @@ -52,6 +79,11 @@ pub struct WalltimeBenchmark { config: BenchmarkConfig, stats: BenchmarkStats, + + /// Rounds in execution order, capped at [`MAX_WALLTIME_ROUNDS_PER_BENCHMARK`]: fewer than + /// `stats.rounds` when subsampled. Left out of the results file. + #[serde(default, skip_serializing_if = "Option::is_none")] + walltime_rounds: Option, } impl WalltimeBenchmark { @@ -116,14 +148,35 @@ impl WalltimeBenchmark { max_time_ns: Option, ) -> Self { let total_time = times_per_round_ns.iter().sum::() as f64 / 1_000_000_000.0; - let time_per_iteration_per_round_ns: Vec<_> = times_per_round_ns - .into_iter() + let mut time_per_iteration_per_round_ns: Vec<_> = times_per_round_ns + .iter() .zip(&iters_per_round) .map(|(time_per_round, iter_per_round)| time_per_round / iter_per_round) .map(|t| t as f64) .collect::>(); - let mut data = Data::new(time_per_iteration_per_round_ns); + // statrs' `quantile` formula (R-8) on rounds sorted once: statrs itself runs an O(n) selection per call + time_per_iteration_per_round_ns.sort_unstable_by(f64::total_cmp); + let sorted = &time_per_iteration_per_round_ns; + let percentiles_ns: Vec = (1..100) + .map(|p| { + let h = (sorted.len() as f64 + 1.0 / 3.0) * (p as f64 / 100.0) + 1.0 / 3.0; + let hf = h as usize; + if hf == 0 { + return sorted[0]; + } + if hf >= sorted.len() { + return sorted[sorted.len() - 1]; + } + let (a, b) = (sorted[hf - 1], sorted[hf]); + a + (h - hf as f64) * (b - a) + }) + .collect(); + let q1_ns = percentiles_ns[24]; + let median_ns = percentiles_ns[49]; + let q3_ns = percentiles_ns[74]; + + let data = Data::new(time_per_iteration_per_round_ns); let rounds = data.len() as u64; let mean_ns = data.mean().unwrap(); @@ -136,10 +189,6 @@ impl WalltimeBenchmark { data.std_dev().unwrap() }; - let q1_ns = data.quantile(0.25); - let median_ns = data.median(); - let q3_ns = data.quantile(0.75); - let iqr_ns = q3_ns - q1_ns; let iqr_outlier_rounds = data .iter() @@ -172,6 +221,7 @@ impl WalltimeBenchmark { q1_ns, median_ns, q3_ns, + percentiles_ns: Some(percentiles_ns), rounds, total_time, iqr_outlier_rounds, @@ -180,6 +230,32 @@ impl WalltimeBenchmark { warmup_iters, }; + let walltime_rounds = if times_per_round_ns.len() <= MAX_WALLTIME_ROUNDS_PER_BENCHMARK { + BenchmarkRounds { + times_per_round_ns, + iters_per_round, + } + } else { + // Floyd's sampling of distinct indices; the set iterates them in execution order + let mut random = vec![0u8; 8 * MAX_WALLTIME_ROUNDS_PER_BENCHMARK]; + getrandom::fill(&mut random).expect("Failed to generate random bytes"); + let mut kept_indices = BTreeSet::new(); + let n = times_per_round_ns.len(); + for (j, r) in (n - MAX_WALLTIME_ROUNDS_PER_BENCHMARK..n).zip(random.chunks_exact(8)) { + let t = (u64::from_ne_bytes(r.try_into().unwrap()) % (j as u64 + 1)) as usize; + if !kept_indices.insert(t) { + kept_indices.insert(j); + } + } + BenchmarkRounds { + times_per_round_ns: kept_indices + .iter() + .map(|&i| times_per_round_ns[i]) + .collect(), + iters_per_round: kept_indices.iter().map(|&i| iters_per_round[i]).collect(), + } + }; + WalltimeBenchmark { metadata: BenchmarkMetadata { name, uri }, config: BenchmarkConfig { @@ -187,6 +263,7 @@ impl WalltimeBenchmark { ..Default::default() }, stats, + walltime_rounds: Some(walltime_rounds), } } @@ -195,8 +272,10 @@ impl WalltimeBenchmark { std::fs::create_dir_all(&output_dir).unwrap(); let bench_id = generate_unique_id(); let output_path = output_dir.join(format!("{bench_id}.json")); - let mut writer = std::fs::File::create(&output_path).expect("Failed to create the file"); - serde_json::to_writer_pretty(&mut writer, self).expect("Failed to write the data"); + let mut writer = std::io::BufWriter::new( + std::fs::File::create(&output_path).expect("Failed to create the file"), + ); + serde_json::to_writer(&mut writer, self).expect("Failed to write the data"); writer.flush().expect("Failed to flush the writer"); } @@ -240,8 +319,10 @@ impl WalltimeResults { ))? .map(|sample| -> Result<_> { let sample = sample?; - serde_json::from_reader::<_, WalltimeBenchmark>(std::fs::File::open(&sample)?) - .context("Failed to read benchmark data") + serde_json::from_reader::<_, WalltimeBenchmark>(BufReader::new(std::fs::File::open( + &sample, + )?)) + .context("Failed to read benchmark data") }) .collect::>>()?; @@ -269,6 +350,21 @@ impl WalltimeResults { pub fn benchmarks(&self) -> &[WalltimeBenchmark] { &self.benchmarks } + + /// Moves the walltime rounds out of the benchmarks; `None` when no benchmark has any + pub fn take_walltime_rounds(&mut self) -> Option { + let benchmarks: Vec<_> = self + .benchmarks + .iter_mut() + .filter_map(|bench| { + Some(UriRounds { + uri: bench.metadata.uri.clone(), + rounds: bench.walltime_rounds.take()?, + }) + }) + .collect(); + (!benchmarks.is_empty()).then_some(WalltimeRounds { benchmarks }) + } } // FIXME: This assumes that the cargo target dir is `target`, and duplicates information with @@ -325,4 +421,118 @@ mod tests { 42. * total_rounds / 1_000_000_000.0 ); } + + #[test] + fn test_percentiles_match_statrs() { + for rounds in [1u128, 2, 3, 10, 100] { + // 1..=rounds in a shuffled execution order + let times: Vec = (1..=rounds).map(|i| i * 37 % (rounds + 1)).collect(); + let benchmark = WalltimeBenchmark::from_runtime_data( + NAME.to_string(), + URI.to_string(), + vec![1; times.len()], + times.clone(), + None, + ); + + let percentiles = benchmark.stats.percentiles_ns.unwrap(); + let mut data = Data::new(times.iter().map(|&t| t as f64).collect::>()); + let expected: Vec = (1..100) + .map(|p| statrs::statistics::OrderStatistics::percentile(&mut data, p)) + .collect(); + assert_eq!(percentiles, expected, "{rounds} rounds"); + assert!(percentiles.windows(2).all(|w| w[0] <= w[1])); + assert_eq!(benchmark.stats.q1_ns, percentiles[24]); + assert_eq!(benchmark.stats.median_ns, percentiles[49]); + assert_eq!(benchmark.stats.q3_ns, percentiles[74]); + } + } + + #[test] + fn test_walltime_rounds_capped_in_execution_order() { + let rounds = MAX_WALLTIME_ROUNDS_PER_BENCHMARK + 50_000; + let iters: Vec = (1..=rounds as u128).collect(); + let times: Vec = iters.iter().map(|i| i * 10).collect(); + let benchmark = WalltimeBenchmark::from_runtime_data( + NAME.to_string(), + URI.to_string(), + iters, + times, + None, + ); + + assert_eq!(benchmark.stats.rounds, rounds as u64); + let kept = benchmark.walltime_rounds.unwrap(); + assert_eq!( + kept.times_per_round_ns.len(), + MAX_WALLTIME_ROUNDS_PER_BENCHMARK + ); + assert_eq!( + kept.iters_per_round.len(), + MAX_WALLTIME_ROUNDS_PER_BENCHMARK + ); + // A random subsample, not the first rounds + assert!(*kept.iters_per_round.last().unwrap() > MAX_WALLTIME_ROUNDS_PER_BENCHMARK as u128); + assert!(kept.times_per_round_ns.windows(2).all(|w| w[0] < w[1])); + assert!(kept + .times_per_round_ns + .iter() + .zip(&kept.iters_per_round) + .all(|(&t, &i)| t == i * 10 && (1..=rounds as u128).contains(&i))); + } + + #[test] + fn test_take_walltime_rounds() { + // A dump from a codspeed version without percentiles nor walltime rounds + let old_dump: WalltimeBenchmark = serde_json::from_value(serde_json::json!({ + "name": "old", "uri": "test::old", "config": {}, + "stats": { + "min_ns": 1.0, "max_ns": 1.0, "mean_ns": 1.0, "stdev_ns": 0.0, + "q1_ns": 1.0, "median_ns": 1.0, "q3_ns": 1.0, "rounds": 1, "total_time": 1e-9, + "iqr_outlier_rounds": 0, "stdev_outlier_rounds": 0, "iter_per_round": 1, "warmup_iters": 0 + } + })) + .unwrap(); + let mut results = WalltimeResults { + creator: Creator { + name: "codspeed-rust".to_string(), + version: "0.0.0".to_string(), + pid: 1, + }, + instrument: Instrument { + type_: "walltime".to_string(), + }, + benchmarks: vec![old_dump], + }; + assert!(results.take_walltime_rounds().is_none()); + + results + .benchmarks + .push(WalltimeBenchmark::from_runtime_data( + NAME.to_string(), + URI.to_string(), + vec![1, 2], + vec![30, 50], + None, + )); + let rounds = serde_json::to_value(results.take_walltime_rounds().unwrap()).unwrap(); + assert_eq!( + rounds, + serde_json::json!({"benchmarks": [ + {"uri": URI, "times_per_round_ns": [30, 50], "iters_per_round": [1, 2]} + ]}) + ); + let results = serde_json::to_value(&results).unwrap(); + assert!(results["benchmarks"][1].get("walltime_rounds").is_none()); + assert_eq!( + results["benchmarks"][1]["stats"]["percentiles_ns"] + .as_array() + .unwrap() + .len(), + 99 + ); + assert!(results["benchmarks"][0]["stats"] + .get("percentiles_ns") + .is_none()); + } }