1use crate::config::{SELF_TOOL, Subject};
17use crate::settings::Settings;
18use anyhow::{Context, Result, bail};
19use std::collections::BTreeMap;
20use std::path::Path;
21use std::process::{Command, Stdio};
22use std::time::Instant;
23
24#[derive(Debug, Clone)]
25pub struct Plan {
26 pub cmd: Vec<String>,
27 pub warmup: u32,
28 pub runs: u32,
29 pub dir: Option<std::path::PathBuf>,
33 pub settings: Settings,
37}
38
39fn subject(bin: &str, settings: &Settings) -> Command {
58 let mut c = Command::new(bin);
59 for key in settings.scrubbed_env() {
60 c.env_remove(key);
61 }
62 c
63}
64
65#[derive(Debug, Clone, Copy)]
67struct Site<'a> {
68 dir: Option<&'a Path>,
69 env: &'a BTreeMap<String, String>,
70 settings: &'a Settings,
71}
72
73fn command(argv: &[String], site: &Site) -> Result<Command> {
79 let (bin, args) = argv.split_first().context("empty command")?;
80 let mut c = subject(bin, site.settings);
81 c.args(args).envs(site.env);
82 if let Some(d) = site.dir {
83 c.current_dir(d);
84 }
85 Ok(c)
86}
87
88fn time_once(cmd: &[String], site: &Site) -> Result<f64> {
94 let mut c = command(cmd, site)?;
95 c.stdout(Stdio::null()).stderr(Stdio::null());
96 let bin = &cmd[0];
97 let start = Instant::now();
98 let status = c
99 .status()
100 .with_context(|| format!("failed to spawn `{bin}`"))?;
101 let elapsed = start.elapsed().as_secs_f64() * 1000.0;
102 if !status.success() {
103 bail!("benchmark subject `{bin}` exited with {status}");
104 }
105 Ok(elapsed)
106}
107
108const PREPARE_STDERR_TAIL: usize = 4096;
112
113fn prepare_once(cmd: &[String], site: &Site) -> Result<()> {
116 use std::io::Read;
117
118 let mut c = command(cmd, site)?;
119 let bin = &cmd[0];
120 let mut child = c
121 .stdin(Stdio::null())
122 .stdout(Stdio::null())
123 .stderr(Stdio::piped())
124 .spawn()
125 .with_context(|| format!("failed to spawn prepare `{bin}`"))?;
126 let mut tail: Vec<u8> = Vec::new();
129 if let Some(mut err) = child.stderr.take() {
130 let mut buf = [0u8; 8192];
131 loop {
132 let n = err.read(&mut buf).unwrap_or(0);
133 if n == 0 {
134 break;
135 }
136 tail.extend_from_slice(&buf[..n]);
137 if tail.len() > PREPARE_STDERR_TAIL {
138 tail.drain(..tail.len() - PREPARE_STDERR_TAIL);
139 }
140 }
141 }
142 let status = child
143 .wait()
144 .with_context(|| format!("failed to wait for prepare `{bin}`"))?;
145 if !status.success() {
146 let stderr = String::from_utf8_lossy(&tail);
147 bail!(
148 "prepare `{bin}` exited with {status}: {}",
149 stderr.lines().last().unwrap_or("(no output)").trim()
150 );
151 }
152 Ok(())
153}
154
155#[derive(Debug, Clone, Copy, PartialEq, Eq)]
157pub struct Slot {
158 pub subject: usize,
160 pub timed: bool,
163}
164
165pub fn schedule(counts: &[(u32, u32)], seed: u64) -> Vec<Slot> {
183 let mut rng = fastrand::Rng::with_seed(seed);
184 let mut out = Vec::new();
185 for timed in [false, true] {
186 let count = |i: usize| {
187 let (warmup, runs) = counts[i];
188 u64::from(if timed { runs } else { warmup })
189 };
190 let rounds = (0..counts.len()).map(count).max().unwrap_or(0);
191 for round in 0..rounds {
192 let mut due: Vec<usize> = (0..counts.len())
195 .filter(|&i| (round + 1) * count(i) / rounds > round * count(i) / rounds)
196 .collect();
197 rng.shuffle(&mut due);
198 out.extend(due.into_iter().map(|subject| Slot { subject, timed }));
199 }
200 }
201 out
202}
203
204pub fn seed_for(seed: u64, bench: &str) -> u64 {
207 bench.bytes().fold(seed ^ 0xcbf2_9ce4_8422_2325, |h, b| {
209 (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3)
210 })
211}
212
213pub fn interleaved(subjects: &[Subject], seed: u64, settings: &Settings) -> Vec<Result<Vec<f64>>> {
221 let counts: Vec<_> = subjects.iter().map(|s| (s.warmup, s.runs)).collect();
222 let mut results: Vec<Result<Vec<f64>>> = subjects
223 .iter()
224 .map(|s| {
225 if s.runs == 0 {
227 bail!("runs must be at least 1");
228 }
229 Ok(Vec::with_capacity(s.runs as usize))
230 })
231 .collect();
232 for slot in schedule(&counts, seed) {
233 let Ok(samples) = &mut results[slot.subject] else {
234 continue;
235 };
236 let s = &subjects[slot.subject];
237 let site = Site {
238 dir: s.dir.as_deref(),
239 env: &s.env,
240 settings,
241 };
242 let taken = s
243 .prepare
244 .as_deref()
245 .map_or(Ok(()), |p| prepare_once(p, &site))
246 .and_then(|()| time_once(&s.cmd, &site));
247 match taken {
248 Ok(ms) if slot.timed => samples.push(ms),
249 Ok(_) => {}
250 Err(e) => results[slot.subject] = Err(e),
251 }
252 }
253 results
254}
255
256pub fn stats(samples: &[f64]) -> BTreeMap<String, f64> {
263 let mut sorted = samples.to_vec();
264 sorted.sort_by(f64::total_cmp);
265 let n = sorted.len();
266 let mean = sorted.iter().sum::<f64>() / n as f64;
267 let stddev = if n > 1 {
269 (sorted.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / (n - 1) as f64).sqrt()
270 } else {
271 0.0
272 };
273 BTreeMap::from([
274 ("wall_min_ms".to_string(), sorted[0]),
275 ("wall_p50_ms".to_string(), sorted[n / 2]),
276 ("wall_mean_ms".to_string(), mean),
277 ("wall_max_ms".to_string(), sorted[n - 1]),
278 ("wall_stddev_ms".to_string(), stddev),
279 ("wall_n".to_string(), n as f64),
280 ])
281}
282
283pub fn wall(plan: &Plan) -> Result<BTreeMap<String, f64>> {
285 let subject = Subject {
286 name: SELF_TOOL.to_string(),
287 cmd: plan.cmd.clone(),
288 prepare: None,
289 dir: plan.dir.clone(),
290 env: BTreeMap::new(),
291 runs: plan.runs,
292 warmup: plan.warmup,
293 counters: false,
294 };
295 let samples = interleaved(std::slice::from_ref(&subject), 0, &plan.settings)
297 .pop()
298 .expect("one result per subject")?;
299 Ok(stats(&samples))
300}
301
302pub fn valgrind_available() -> bool {
308 Command::new("valgrind")
309 .arg("--version")
310 .stdout(Stdio::null())
311 .stderr(Stdio::null())
312 .status()
313 .map(|s| s.success())
314 .unwrap_or(false)
315}
316
317const COUNTER_RUNS: u32 = 3;
320
321const SPREAD_WARN_PCT: f64 = 0.5;
326
327#[derive(Debug, Clone, Copy)]
329pub struct Counted {
330 pub min: u64,
331 pub max: u64,
332 pub runs: u32,
333}
334
335impl Counted {
336 pub fn spread_pct(&self) -> f64 {
338 if self.min == 0 {
339 return 0.0;
340 }
341 (self.max - self.min) as f64 / self.min as f64 * 100.0
342 }
343
344 pub fn is_suspect(&self) -> bool {
351 self.spread_pct() > SPREAD_WARN_PCT
352 }
353}
354
355pub fn instructions(
367 cmd: &[String],
368 dir: Option<&std::path::Path>,
369 settings: &Settings,
370) -> Result<Option<Counted>> {
371 count(
372 cmd,
373 None,
374 &Site {
375 dir,
376 env: &BTreeMap::new(),
377 settings,
378 },
379 )
380}
381
382pub fn subject_instructions(s: &Subject, settings: &Settings) -> Result<Option<Counted>> {
386 count(
387 &s.cmd,
388 s.prepare.as_deref(),
389 &Site {
390 dir: s.dir.as_deref(),
391 env: &s.env,
392 settings,
393 },
394 )
395}
396
397fn count(cmd: &[String], prepare: Option<&[String]>, site: &Site) -> Result<Option<Counted>> {
398 if !valgrind_available() {
399 return Ok(None);
400 }
401
402 let mut samples: Vec<u64> = Vec::with_capacity(COUNTER_RUNS as usize);
403 for _ in 0..COUNTER_RUNS {
404 if let Some(p) = prepare {
405 prepare_once(p, site)?;
406 }
407 let mut argv: Vec<String> = [
408 "valgrind",
409 "--tool=cachegrind",
410 "--cache-sim=no",
411 "--branch-sim=no",
412 "--cachegrind-out-file=/dev/null",
413 ]
414 .map(String::from)
415 .to_vec();
416 argv.extend_from_slice(cmd);
417 let mut c = command(&argv, site)?;
418 c.stdout(Stdio::null());
419 let out = c.output().context("failed to run valgrind")?;
420
421 let stderr = String::from_utf8_lossy(&out.stderr);
423 if !out.status.success() {
424 let bin = cmd.first().map(String::as_str).unwrap_or("(empty command)");
425 bail!(
426 "benchmark subject `{bin}` exited with {} under valgrind",
427 out.status
428 );
429 }
430 match parse_irefs(&stderr) {
431 Some(n) => samples.push(n),
432 None => bail!(
436 "valgrind ran but emitted no `I refs` summary: {}",
437 stderr.lines().last().unwrap_or("(no output)").trim()
438 ),
439 }
440 }
441
442 Ok(Some(Counted {
443 min: *samples.iter().min().expect("COUNTER_RUNS > 0"),
444 max: *samples.iter().max().expect("COUNTER_RUNS > 0"),
445 runs: COUNTER_RUNS,
446 }))
447}
448
449fn parse_irefs(stderr: &str) -> Option<u64> {
451 let line = stderr.lines().find(|l| l.contains("I refs:"))?;
452 let digits: String = line
453 .rsplit(':')
454 .next()?
455 .chars()
456 .filter(|c| c.is_ascii_digit())
457 .collect();
458 digits.parse().ok()
459}
460
461#[cfg(test)]
462mod tests {
463 use super::*;
464
465 #[test]
466 fn parses_cachegrind_summary() {
467 let s = "==12== I refs: 48,349,132\n";
468 assert_eq!(parse_irefs(s), Some(48_349_132));
469 }
470
471 #[test]
472 fn missing_summary_is_none_not_panic() {
473 assert_eq!(parse_irefs("valgrind: command not found"), None);
474 }
475
476 fn removals(settings: &Settings) -> Vec<String> {
478 subject("true", settings)
479 .get_envs()
480 .filter(|(_, v)| v.is_none())
481 .map(|(k, _)| k.to_string_lossy().into_owned())
482 .collect()
483 }
484
485 #[test]
488 fn subject_commands_remove_the_default_denied_variables() {
489 let removed = removals(&Settings::default());
490 for key in Settings::default().scrubbed_env() {
491 assert!(removed.contains(&key.to_string()), "{key} not removed");
492 }
493 }
494
495 #[test]
498 fn the_removal_follows_the_settings() {
499 let removed = removals(&Settings {
500 env_deny: vec!["CUSTOM_SECRET".into()],
501 env_allow: Vec::new(),
502 ..Settings::default()
503 });
504 assert!(removed.contains(&"CUSTOM_SECRET".to_string()));
505 assert!(!removed.contains(&"GITHUB_TOKEN".to_string()));
506 }
507
508 #[test]
511 fn an_allowed_variable_survives() {
512 let removed = removals(&Settings {
513 env_deny: vec!["GITHUB_TOKEN".into(), "GH_TOKEN".into()],
514 env_allow: vec!["GITHUB_TOKEN".into()],
515 ..Settings::default()
516 });
517 assert!(!removed.contains(&"GITHUB_TOKEN".to_string()));
518 assert!(removed.contains(&"GH_TOKEN".to_string()));
519 }
520
521 #[test]
522 fn zero_runs_is_rejected_not_a_panic() {
523 let plan = Plan {
524 cmd: vec!["true".into()],
525 warmup: 0,
526 runs: 0,
527 dir: None,
528 settings: Settings::default(),
529 };
530 assert!(wall(&plan).is_err());
531 }
532
533 #[test]
534 fn a_failed_subject_is_not_recorded_as_a_fast_run() {
535 #[cfg(unix)]
536 let cmd = vec!["/bin/sh".into(), "-c".into(), "exit 42".into()];
537 #[cfg(windows)]
538 let cmd = vec!["cmd".into(), "/C".into(), "exit /B 42".into()];
539
540 let err = wall(&Plan {
541 cmd,
542 warmup: 0,
543 runs: 1,
544 dir: None,
545 settings: Settings::default(),
546 })
547 .unwrap_err();
548
549 assert!(format!("{err:#}").contains("exited with"), "{err:#}");
550 }
551
552 #[test]
553 fn wall_reports_min_le_p50_le_max() {
554 let plan = Plan {
555 cmd: vec!["true".into()],
556 warmup: 1,
557 runs: 5,
558 dir: None,
559 settings: Settings::default(),
560 };
561 let m = wall(&plan).unwrap();
562 assert!(m["wall_min_ms"] <= m["wall_p50_ms"]);
563 assert!(m["wall_p50_ms"] <= m["wall_max_ms"]);
564 assert_eq!(m["wall_n"], 5.0);
565 }
566
567 #[test]
569 fn the_schedule_gives_each_subject_its_counts() {
570 let counts = [(2, 10), (1, 5), (0, 3)];
571 let order = schedule(&counts, 7);
572 for (i, &(warmup, runs)) in counts.iter().enumerate() {
573 let of = |timed| {
574 order
575 .iter()
576 .filter(|s| s.subject == i && s.timed == timed)
577 .count()
578 };
579 assert_eq!(of(false), warmup as usize, "subject {i} warmups");
580 assert_eq!(of(true), runs as usize, "subject {i} runs");
581 }
582 let first_timed = order.iter().position(|s| s.timed).unwrap();
583 assert!(order[first_timed..].iter().all(|s| s.timed));
584 }
585
586 #[test]
587 fn the_same_seed_gives_the_same_order() {
588 let counts = [(1, 8), (1, 8), (1, 8)];
589 assert_eq!(schedule(&counts, 42), schedule(&counts, 42));
590 assert_ne!(schedule(&counts, 42), schedule(&counts, 43));
591 }
592
593 #[test]
596 fn each_round_runs_every_subject_once_in_a_varying_order() {
597 let order = schedule(&[(0, 20), (0, 20), (0, 20)], 1);
598 let rounds: Vec<Vec<usize>> = order
599 .chunks(3)
600 .map(|r| r.iter().map(|s| s.subject).collect())
601 .collect();
602 assert_eq!(rounds.len(), 20);
603 for r in &rounds {
604 let mut sorted = r.clone();
605 sorted.sort();
606 assert_eq!(sorted, [0, 1, 2], "round {r:?}");
607 }
608 assert!(rounds.iter().any(|r| r != &rounds[0]), "never shuffled");
609 }
610
611 #[test]
614 fn a_subject_with_fewer_runs_is_spread_across_the_run() {
615 let order = schedule(&[(0, 10), (0, 5)], 3);
616 let fewer: Vec<usize> = order
617 .iter()
618 .enumerate()
619 .filter(|(_, s)| s.subject == 1)
620 .map(|(i, _)| i)
621 .collect();
622 assert_eq!(fewer.len(), 5);
623 assert!(
624 *fewer.last().unwrap() >= order.len() - 3,
625 "last sample of the smaller subject is near the end: {fewer:?} of {}",
626 order.len()
627 );
628 }
629
630 #[test]
631 fn a_benchmark_seed_depends_on_its_name_and_the_run_seed() {
632 assert_eq!(seed_for(1, "a"), seed_for(1, "a"));
633 assert_ne!(seed_for(1, "a"), seed_for(1, "b"));
634 assert_ne!(seed_for(1, "a"), seed_for(2, "a"));
635 }
636
637 #[test]
638 fn stats_report_the_sample_standard_deviation() {
639 let m = stats(&[2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0]);
640 assert_eq!(m["wall_min_ms"], 2.0);
641 assert_eq!(m["wall_max_ms"], 9.0);
642 assert_eq!(m["wall_mean_ms"], 5.0);
643 assert!((m["wall_stddev_ms"] - 2.138_089_935).abs() < 1e-6);
645 assert_eq!(stats(&[3.0])["wall_stddev_ms"], 0.0);
646 }
647
648 #[cfg(unix)]
650 #[test]
651 fn a_failing_subject_does_not_stop_the_others() {
652 let mk = |name: &str, cmd: &[&str]| Subject {
653 name: name.into(),
654 cmd: cmd.iter().map(|s| s.to_string()).collect(),
655 prepare: None,
656 dir: None,
657 env: BTreeMap::new(),
658 runs: 4,
659 warmup: 1,
660 counters: false,
661 };
662 let res = interleaved(
663 &[mk("ok", &["true"]), mk("bad", &["false"])],
664 5,
665 &Settings::default(),
666 );
667 assert_eq!(res[0].as_ref().unwrap().len(), 4);
668 assert!(format!("{:#}", res[1].as_ref().unwrap_err()).contains("exited with"));
669 }
670
671 #[cfg(unix)]
673 #[test]
674 fn a_failing_prepare_is_reported_as_prepare() {
675 let res = interleaved(
676 &[Subject {
677 name: "x".into(),
678 cmd: vec!["true".into()],
679 prepare: Some(vec![
680 "/bin/sh".into(),
681 "-c".into(),
682 "echo nope >&2; exit 3".into(),
683 ]),
684 dir: None,
685 env: BTreeMap::new(),
686 runs: 1,
687 warmup: 0,
688 counters: false,
689 }],
690 0,
691 &Settings::default(),
692 );
693 let msg = format!("{:#}", res[0].as_ref().unwrap_err());
694 assert!(msg.contains("prepare") && msg.contains("nope"), "{msg}");
695 }
696}