| 1 |
use anyhow::{Context, Result}; |
| 2 |
use std::{ |
| 3 |
io::Write, |
| 4 |
path::{Path, PathBuf}, |
| 5 |
}; |
| 6 |
|
| 7 |
use serde::{Deserialize, Serialize}; |
| 8 |
use statrs::statistics::{Data, Distribution, Max, Min, OrderStatistics}; |
| 9 |
|
| 10 |
use crate::utils::generate_unique_id; |
| 11 |
|
| 12 |
const IQR_OUTLIER_FACTOR: f64 = 1.5; |
| 13 |
const STDEV_OUTLIER_FACTOR: f64 = 3.0; |
| 14 |
|
| 15 |
#[derive(Debug, Serialize, Deserialize)] |
| 16 |
pub struct BenchmarkMetadata { |
| 17 |
pub name: String, |
| 18 |
pub uri: String, |
| 19 |
} |
| 20 |
|
| 21 |
#[derive(Debug, Serialize, Deserialize)] |
| 22 |
struct BenchmarkStats { |
| 23 |
min_ns: f64, |
| 24 |
max_ns: f64, |
| 25 |
mean_ns: f64, |
| 26 |
stdev_ns: f64, |
| 27 |
|
| 28 |
q1_ns: f64, |
| 29 |
median_ns: f64, |
| 30 |
q3_ns: f64, |
| 31 |
|
| 32 |
rounds: u64, |
| 33 |
total_time: f64, |
| 34 |
iqr_outlier_rounds: u64, |
| 35 |
stdev_outlier_rounds: u64, |
| 36 |
iter_per_round: u64, |
| 37 |
warmup_iters: u64, |
| 38 |
} |
| 39 |
|
| 40 |
#[derive(Debug, Serialize, Deserialize, Default)] |
| 41 |
struct BenchmarkConfig { |
| 42 |
warmup_time_ns: Option<f64>, |
| 43 |
min_round_time_ns: Option<f64>, |
| 44 |
max_time_ns: Option<f64>, |
| 45 |
max_rounds: Option<u64>, |
| 46 |
} |
| 47 |
|
| 48 |
#[derive(Debug, Serialize, Deserialize)] |
| 49 |
pub struct WalltimeBenchmark { |
| 50 |
#[serde(flatten)] |
| 51 |
metadata: BenchmarkMetadata, |
| 52 |
|
| 53 |
config: BenchmarkConfig, |
| 54 |
stats: BenchmarkStats, |
| 55 |
} |
| 56 |
|
| 57 |
impl WalltimeBenchmark { |
| 58 |
/// Entry point called in patched integration to harvest raw walltime data |
| 59 |
/// |
| 60 |
/// `CODSPEED_CARGO_WORKSPACE_ROOT` is expected to be set for this to work |
| 61 |
/// |
| 62 |
/// # Arguments |
| 63 |
/// |
| 64 |
/// - `scope`: The used integration, e.g. "divan" or "criterion" |
| 65 |
/// - `name`: The name of the benchmark |
| 66 |
/// - `uri`: The URI of the benchmark |
| 67 |
/// - `iters_per_round`: The number of iterations for each round (=sample_size), e.g. `[1, 2, 3]` (variable) or `[2, 2, 2, 2]` (constant). |
| 68 |
/// - `times_per_round_ns`: The measured time for each round in nanoseconds, e.g. `[1000, 2000, 3000]` |
| 69 |
/// - `max_time_ns`: The time limit for the benchmark in nanoseconds (if defined) |
| 70 |
/// |
| 71 |
/// # Pseudo-code |
| 72 |
/// |
| 73 |
/// ```text |
| 74 |
/// let sample_count = /* The number of executions for the same benchmark. */ |
| 75 |
/// let sample_size = iters_per_round = vec![/* The number of iterations within each sample. */]; |
| 76 |
/// for round in 0..sample_count { |
| 77 |
/// let times_per_round_ns = 0; |
| 78 |
/// for iteration in 0..sample_size[round] { |
| 79 |
/// run_benchmark(); |
| 80 |
/// times_per_round_ns += /* measured execution time */; |
| 81 |
/// } |
| 82 |
/// } |
| 83 |
/// ``` |
| 84 |
/// |
| 85 |
pub fn collect_raw_walltime_results( |
| 86 |
scope: &str, |
| 87 |
name: String, |
| 88 |
uri: String, |
| 89 |
iters_per_round: Vec<u128>, |
| 90 |
times_per_round_ns: Vec<u128>, |
| 91 |
max_time_ns: Option<u128>, |
| 92 |
) { |
| 93 |
if !crate::utils::running_with_codspeed_runner() { |
| 94 |
return; |
| 95 |
} |
| 96 |
let workspace_root = std::env::var("CODSPEED_CARGO_WORKSPACE_ROOT").map(PathBuf::from); |
| 97 |
let Ok(workspace_root) = workspace_root else { |
| 98 |
eprintln!("codspeed failed to get workspace root. skipping"); |
| 99 |
return; |
| 100 |
}; |
| 101 |
let data = WalltimeBenchmark::from_runtime_data( |
| 102 |
name, |
| 103 |
uri, |
| 104 |
iters_per_round, |
| 105 |
times_per_round_ns, |
| 106 |
max_time_ns, |
| 107 |
); |
| 108 |
data.dump_to_results(&workspace_root, scope); |
| 109 |
} |
| 110 |
|
| 111 |
pub fn from_runtime_data( |
| 112 |
name: String, |
| 113 |
uri: String, |
| 114 |
iters_per_round: Vec<u128>, |
| 115 |
times_per_round_ns: Vec<u128>, |
| 116 |
max_time_ns: Option<u128>, |
| 117 |
) -> Self { |
| 118 |
let total_time = times_per_round_ns.iter().sum::<u128>() as f64 / 1_000_000_000.0; |
| 119 |
let time_per_iteration_per_round_ns: Vec<_> = times_per_round_ns |
| 120 |
.into_iter() |
| 121 |
.zip(&iters_per_round) |
| 122 |
.map(|(time_per_round, iter_per_round)| time_per_round / iter_per_round) |
| 123 |
.map(|t| t as f64) |
| 124 |
.collect::<Vec<f64>>(); |
| 125 |
|
| 126 |
let mut data = Data::new(time_per_iteration_per_round_ns); |
| 127 |
let rounds = data.len() as u64; |
| 128 |
|
| 129 |
let mean_ns = data.mean().unwrap(); |
| 130 |
|
| 131 |
let stdev_ns = if data.len() < 2 { |
| 132 |
// std_dev() returns f64::NAN if data has less than two entries, so we have to |
| 133 |
// manually handle this case. |
| 134 |
0.0 |
| 135 |
} else { |
| 136 |
data.std_dev().unwrap() |
| 137 |
}; |
| 138 |
|
| 139 |
let q1_ns = data.quantile(0.25); |
| 140 |
let median_ns = data.median(); |
| 141 |
let q3_ns = data.quantile(0.75); |
| 142 |
|
| 143 |
let iqr_ns = q3_ns - q1_ns; |
| 144 |
let iqr_outlier_rounds = data |
| 145 |
.iter() |
| 146 |
.filter(|&&t| { |
| 147 |
t < q1_ns - IQR_OUTLIER_FACTOR * iqr_ns || t > q3_ns + IQR_OUTLIER_FACTOR * iqr_ns |
| 148 |
}) |
| 149 |
.count() as u64; |
| 150 |
|
| 151 |
let stdev_outlier_rounds = data |
| 152 |
.iter() |
| 153 |
.filter(|&&t| { |
| 154 |
t < mean_ns - STDEV_OUTLIER_FACTOR * stdev_ns |
| 155 |
|| t > mean_ns + STDEV_OUTLIER_FACTOR * stdev_ns |
| 156 |
}) |
| 157 |
.count() as u64; |
| 158 |
|
| 159 |
let min_ns = data.min(); |
| 160 |
let max_ns = data.max(); |
| 161 |
|
| 162 |
// TODO(COD-1056): We currently only support single iteration count per round |
| 163 |
let iter_per_round = |
| 164 |
(iters_per_round.iter().sum::<u128>() / iters_per_round.len() as u128) as u64; |
| 165 |
let warmup_iters = 0; // FIXME: add warmup detection |
| 166 |
|
| 167 |
let stats = BenchmarkStats { |
| 168 |
min_ns, |
| 169 |
max_ns, |
| 170 |
mean_ns, |
| 171 |
stdev_ns, |
| 172 |
q1_ns, |
| 173 |
median_ns, |
| 174 |
q3_ns, |
| 175 |
rounds, |
| 176 |
total_time, |
| 177 |
iqr_outlier_rounds, |
| 178 |
stdev_outlier_rounds, |
| 179 |
iter_per_round, |
| 180 |
warmup_iters, |
| 181 |
}; |
| 182 |
|
| 183 |
WalltimeBenchmark { |
| 184 |
metadata: BenchmarkMetadata { name, uri }, |
| 185 |
config: BenchmarkConfig { |
| 186 |
max_time_ns: max_time_ns.map(|t| t as f64), |
| 187 |
..Default::default() |
| 188 |
}, |
| 189 |
stats, |
| 190 |
} |
| 191 |
} |
| 192 |
|
| 193 |
fn dump_to_results(&self, workspace_root: &Path, scope: &str) { |
| 194 |
let output_dir = result_dir_from_workspace_root(workspace_root).join(scope); |
| 195 |
std::fs::create_dir_all(&output_dir).unwrap(); |
| 196 |
let bench_id = generate_unique_id(); |
| 197 |
let output_path = output_dir.join(format!("{bench_id}.json")); |
| 198 |
let mut writer = std::fs::File::create(&output_path).expect("Failed to create the file"); |
| 199 |
serde_json::to_writer_pretty(&mut writer, self).expect("Failed to write the data"); |
| 200 |
writer.flush().expect("Failed to flush the writer"); |
| 201 |
} |
| 202 |
|
| 203 |
pub fn is_invalid(&self) -> bool { |
| 204 |
self.stats.min_ns < f64::EPSILON |
| 205 |
} |
| 206 |
|
| 207 |
pub fn name(&self) -> &str { |
| 208 |
&self.metadata.name |
| 209 |
} |
| 210 |
} |
| 211 |
|
| 212 |
#[derive(Debug, Serialize, Deserialize)] |
| 213 |
struct Instrument { |
| 214 |
#[serde(rename = "type")] |
| 215 |
type_: String, |
| 216 |
} |
| 217 |
|
| 218 |
#[derive(Debug, Serialize, Deserialize)] |
| 219 |
struct Creator { |
| 220 |
name: String, |
| 221 |
version: String, |
| 222 |
pid: u32, |
| 223 |
} |
| 224 |
|
| 225 |
#[derive(Debug, Serialize, Deserialize)] |
| 226 |
pub struct WalltimeResults { |
| 227 |
creator: Creator, |
| 228 |
instrument: Instrument, |
| 229 |
benchmarks: Vec<WalltimeBenchmark>, |
| 230 |
} |
| 231 |
|
| 232 |
impl WalltimeResults { |
| 233 |
pub fn collect_walltime_results(workspace_root: &Path) -> Result<Self> { |
| 234 |
// retrieve data from `{workspace_root}/target/codspeed/raw_results/{scope}/*.json |
| 235 |
let benchmarks = glob::glob(&format!( |
| 236 |
"{}/**/*.json", |
| 237 |
result_dir_from_workspace_root(workspace_root) |
| 238 |
.to_str() |
| 239 |
.unwrap(), |
| 240 |
))? |
| 241 |
.map(|sample| -> Result<_> { |
| 242 |
let sample = sample?; |
| 243 |
serde_json::from_reader::<_, WalltimeBenchmark>(std::fs::File::open(&sample)?) |
| 244 |
.context("Failed to read benchmark data") |
| 245 |
}) |
| 246 |
.collect::<Result<Vec<_>>>()?; |
| 247 |
|
| 248 |
Ok(WalltimeResults { |
| 249 |
instrument: Instrument { |
| 250 |
type_: "walltime".to_string(), |
| 251 |
}, |
| 252 |
creator: Creator { |
| 253 |
name: "codspeed-rust".to_string(), |
| 254 |
version: env!("CARGO_PKG_VERSION").to_string(), |
| 255 |
pid: std::process::id(), |
| 256 |
}, |
| 257 |
benchmarks, |
| 258 |
}) |
| 259 |
} |
| 260 |
|
| 261 |
pub fn clear(workspace_root: &Path) -> Result<()> { |
| 262 |
let raw_results_dir = result_dir_from_workspace_root(workspace_root); |
| 263 |
std::fs::remove_dir_all(&raw_results_dir).ok(); // ignore errors when the directory does not exist |
| 264 |
std::fs::create_dir_all(&raw_results_dir) |
| 265 |
.context("Failed to create raw_results directory")?; |
| 266 |
Ok(()) |
| 267 |
} |
| 268 |
|
| 269 |
pub fn benchmarks(&self) -> &[WalltimeBenchmark] { |
| 270 |
&self.benchmarks |
| 271 |
} |
| 272 |
} |
| 273 |
|
| 274 |
// FIXME: This assumes that the cargo target dir is `target`, and duplicates information with |
| 275 |
// `cargo-codspeed::helpers::get_codspeed_target_dir` |
| 276 |
fn result_dir_from_workspace_root(workspace_root: &Path) -> PathBuf { |
| 277 |
workspace_root |
| 278 |
.join("target") |
| 279 |
.join("codspeed") |
| 280 |
.join("walltime") |
| 281 |
.join("raw_results") |
| 282 |
} |
| 283 |
|
| 284 |
#[cfg(test)] |
| 285 |
mod tests { |
| 286 |
use super::*; |
| 287 |
|
| 288 |
const NAME: &str = "benchmark"; |
| 289 |
const URI: &str = "test::benchmark"; |
| 290 |
|
| 291 |
#[test] |
| 292 |
fn test_parse_single_benchmark() { |
| 293 |
let benchmark = WalltimeBenchmark::from_runtime_data( |
| 294 |
NAME.to_string(), |
| 295 |
URI.to_string(), |
| 296 |
vec![1], |
| 297 |
vec![42], |
| 298 |
None, |
| 299 |
); |
| 300 |
assert_eq!(benchmark.stats.stdev_ns, 0.); |
| 301 |
assert_eq!(benchmark.stats.min_ns, 42.); |
| 302 |
assert_eq!(benchmark.stats.max_ns, 42.); |
| 303 |
assert_eq!(benchmark.stats.mean_ns, 42.); |
| 304 |
} |
| 305 |
|
| 306 |
#[test] |
| 307 |
fn test_parse_bench_with_variable_iterations() { |
| 308 |
let iters_per_round = vec![1, 2, 3, 4, 5, 6]; |
| 309 |
let total_rounds = iters_per_round.iter().sum::<u128>() as f64; |
| 310 |
|
| 311 |
let benchmark = WalltimeBenchmark::from_runtime_data( |
| 312 |
NAME.to_string(), |
| 313 |
URI.to_string(), |
| 314 |
iters_per_round, |
| 315 |
vec![42, 42 * 2, 42 * 3, 42 * 4, 42 * 5, 42 * 6], |
| 316 |
None, |
| 317 |
); |
| 318 |
|
| 319 |
assert_eq!(benchmark.stats.stdev_ns, 0.); |
| 320 |
assert_eq!(benchmark.stats.min_ns, 42.); |
| 321 |
assert_eq!(benchmark.stats.max_ns, 42.); |
| 322 |
assert_eq!(benchmark.stats.mean_ns, 42.); |
| 323 |
assert_eq!( |
| 324 |
benchmark.stats.total_time, |
| 325 |
42. * total_rounds / 1_000_000_000.0 |
| 326 |
); |
| 327 |
} |
| 328 |
} |