Skip to content

Don't rewrite it in Rust. Rewrite the 5% that's slow: profile your app, port the hot functions with your coding agent, prove they behave the same. Python, JS/TS, Ruby, Java, Kotlin, Go, PHP, C/C++, C#, R.

bench: an A/A control, a verdict and CPU time

Milosz27cb33ff201b
diff --git a/Cargo.lock b/Cargo.lock
index 3eaa5f0..97ae569 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -116,6 +116,7 @@ version = "0.8.7"
dependencies = [
"anyhow",
"clap",
+ "libc",
"libloading",
"serde",
"serde_json",
@@ -139,6 +140,12 @@ version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
+[[package]]
+name = "libc"
+version = "0.2.191"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
+
[[package]]
name = "libloading"
version = "0.9.1"
diff --git a/Cargo.toml b/Cargo.toml
index 38ed4fb..f6e32d4 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -22,6 +22,9 @@ libloading = "0.9.1"
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.154"
+[target.'cfg(unix)'.dependencies]
+libc = "0.2.191"
+
[profile.release]
lto = "fat"
codegen-units = 1
diff --git a/README.md b/README.md
index 259c15e..d29697f 100644
--- a/README.md
+++ b/README.md
@@ -46,7 +46,7 @@ Or step by step:
| `port [id]` | records up to 500 real calls, creates a one-function Rust crate + `TASK.md` |
| `verify` | release-builds the port and replays every recorded call |
| `enable` / `disable` | swaps the Rust in or out (one marked block, removed byte for byte) |
-| `bench` | times the whole app, original vs Rust, interleaved runs |
+| `bench` | times the whole app in rotated rounds of original, original again (an A/A control for noise) and Rust; wall and CPU time |
| `report` | markdown + SVG card for your PR |
| `doctor` | checks Rust, your runtimes and your agents |
diff --git a/src/bench.rs b/src/bench.rs
index 106e500..1eb1b9f 100644
--- a/src/bench.rs
+++ b/src/bench.rs
@@ -1,4 +1,5 @@
-//! Times the whole app: original Python vs Rust ports, interleaved so drift hits both equally.
+//! Times the whole app in rounds of original, original again (an A/A control) and Rust, rotated so
+//! drift hits every side equally. Wall time decides; CPU time shows what the ports cost in cores.
use crate::backend::Lang;
use crate::python::DISABLE_ENV;
@@ -6,7 +7,8 @@ use crate::state::Ctx;
use crate::{ui, util};
use anyhow::{Context, Result, ensure};
use serde::{Deserialize, Serialize};
-use std::process::{Command, Stdio};
+use std::io::Read;
+use std::process::{Command, Output, Stdio};
use std::time::Instant;
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
@@ -34,6 +36,68 @@ impl Stats {
}
}
+/// Median and quartiles of per-round values.
+#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
+#[serde(default)]
+pub struct Spread {
+ pub median: f64,
+ pub q1: f64,
+ pub q3: f64,
+}
+
+impl Spread {
+ pub fn of(xs: &[f64]) -> Spread {
+ let (q1, q3) = quartiles(xs);
+ Spread { median: Stats::of(xs).median, q1, q3 }
+ }
+
+ /// How far the middle half reaches from zero: the run-to-run noise for an A/A change.
+ pub fn band(&self) -> f64 {
+ self.q1.abs().max(self.q3.abs())
+ }
+}
+
+/// First and third quartile, computed like Python's statistics.quantiles(n=4) (exclusive).
+fn quartiles(xs: &[f64]) -> (f64, f64) {
+ let mut v = xs.to_vec();
+ v.sort_by(f64::total_cmp);
+ let n = v.len();
+ if n == 0 {
+ return (0.0, 0.0);
+ }
+ if n < 4 {
+ return (v[0], v[n - 1]);
+ }
+ let m = n + 1;
+ let q = |i: usize| {
+ let j = (i * m / 4).clamp(1, n - 1);
+ let d = (i * m - 4 * j) as f64;
+ (v[j - 1] * (4.0 - d) + v[j] * d) / 4.0
+ };
+ (q(1), q(3))
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Verdict {
+ Faster,
+ Slower,
+ /// The Rust rounds don't clear the A/A noise band.
+ Noise,
+}
+
+/// Faster or slower only when the middle half of the Rust changes lies outside the A/A noise band.
+fn verdict(aa: &Spread, change: &Spread) -> Verdict {
+ let band = aa.band();
+ if change.q3 < -band {
+ Verdict::Faster
+ } else if change.q1 > band {
+ Verdict::Slower
+ } else {
+ Verdict::Noise
+ }
+}
+
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct BenchResult {
@@ -43,15 +107,77 @@ pub struct BenchResult {
pub ports: Vec<String>,
pub before: Stats,
pub after: Stats,
+ /// Median over rounds of original time / Rust time, paired within each round.
pub speedup: f64,
- /// First line where the app's output with the Rust ports differs from the original's.
+ pub speedup_q1: f64,
+ pub speedup_q3: f64,
+ /// The original against itself in each round, in %: how much the app varies on its own.
+ pub aa: Spread,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub verdict: Option<Verdict>,
+ /// CPU time (user + system) of the app and the processes it waited for, when the OS tells.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub cpu_before: Option<Stats>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub cpu_after: Option<Stats>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub cpu_speedup: Option<f64>,
+ /// First line where the app's output with the Rust ports differs from the original's,
+ /// or OUTPUT_VARIES.
#[serde(skip_serializing_if = "Option::is_none")]
pub output_diff: Option<String>,
}
-/// One run of the app: how long it took and what it printed.
-fn time_once(ctx: &Ctx, python: &str, args: &[String], original: bool) -> Result<(f64, Vec<u8>)> {
- let mut cmd = Command::new(python);
+impl BenchResult {
+ /// "CPU time 95×", or how much more CPU time the Rust ports take.
+ pub fn cpu_note(&self) -> Option<String> {
+ self.cpu_speedup.map(|x| {
+ if x >= 1.0 {
+ format!("CPU time {}", util::times(x))
+ } else {
+ format!("CPU time {} more", util::times(1.0 / x))
+ }
+ })
+ }
+}
+
+pub const OUTPUT_VARIES: &str =
+ "the original prints something different from run to run, so its output can't be compared with the Rust ports'";
+
+/// Whether the Rust runs print what the original did, checked against every run of the original.
+struct OutputCheck {
+ first: Vec<u8>,
+ varies: bool,
+ rust_diff: Option<String>,
+}
+
+impl OutputCheck {
+ fn new(first: Vec<u8>) -> OutputCheck {
+ OutputCheck { first, varies: false, rust_diff: None }
+ }
+
+ fn see(&mut self, original: bool, out: &[u8]) {
+ if original {
+ self.varies |= out != self.first;
+ } else if self.rust_diff.is_none() {
+ self.rust_diff = first_difference(&self.first, out);
+ }
+ }
+
+ fn diff(self) -> Option<String> {
+ if self.varies { Some(OUTPUT_VARIES.into()) } else { self.rust_diff }
+ }
+}
+
+/// One run of the app: wall time, CPU time if the OS tells, and what it printed.
+struct Run {
+ wall: f64,
+ cpu: Option<f64>,
+ stdout: Vec<u8>,
+}
+
+fn time_once(ctx: &Ctx, exe: &str, args: &[String], original: bool) -> Result<Run> {
+ let mut cmd = Command::new(exe);
cmd.args(args).current_dir(&ctx.root).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
if original {
cmd.env(DISABLE_ENV, "1");
@@ -59,8 +185,8 @@ fn time_once(ctx: &Ctx, python: &str, args: &[String], original: bool) -> Result
cmd.env_remove(DISABLE_ENV);
}
let start = Instant::now();
- let out = cmd.output().context("running the app")?;
- let took = start.elapsed().as_secs_f64();
+ let (out, cpu) = output_with_cpu(&mut cmd).context("running the app")?;
+ let wall = start.elapsed().as_secs_f64();
ensure!(
out.status.success(),
"the app failed ({}) with the {} version:\n{}",
@@ -68,7 +194,181 @@ fn time_once(ctx: &Ctx, python: &str, args: &[String], original: bool) -> Result
if original { ctx.state.lang.label() } else { "Rust" },
util::tail(&String::from_utf8_lossy(&out.stderr), 20)
);
- Ok((took, out.stdout))
+ Ok(Run { wall, cpu, stdout: out.stdout })
+}
+
+/// Like Command::output, plus the CPU time of the child and everything it waited for.
+fn output_with_cpu(cmd: &mut Command) -> std::io::Result<(Output, Option<f64>)> {
+ let mut meter = cpu::Meter::start();
+ let mut child = cmd.spawn()?;
+ meter.attach(&child);
+ let (stdout, stderr) = (child.stdout.take(), child.stderr.take());
+ // stderr on its own thread so neither pipe fills up while the other is read
+ let errors = std::thread::spawn(move || {
+ let mut buf = Vec::new();
+ if let Some(mut e) = stderr {
+ let _ = e.read_to_end(&mut buf);
+ }
+ buf
+ });
+ let mut out = Vec::new();
+ if let Some(mut o) = stdout {
+ o.read_to_end(&mut out)?;
+ }
+ let err = errors.join().unwrap_or_default();
+ let status = child.wait()?;
+ Ok((Output { status, stdout: out, stderr: err }, meter.stop()))
+}
+
+#[cfg(unix)]
+mod cpu {
+ use std::process::Child;
+
+ /// CPU seconds of every child this process has waited for, and their waited-for children.
+ fn children() -> Option<f64> {
+ // SAFETY: getrusage only writes into the struct it's given.
+ let mut usage: libc::rusage = unsafe { std::mem::zeroed() };
+ if unsafe { libc::getrusage(libc::RUSAGE_CHILDREN, &mut usage) } != 0 {
+ return None;
+ }
+ let secs = |t: libc::timeval| t.tv_sec as f64 + t.tv_usec as f64 / 1e6;
+ Some(secs(usage.ru_utime) + secs(usage.ru_stime))
+ }
+
+ /// The children's total before the run; the run is the difference after waiting for it.
+ pub struct Meter(Option<f64>);
+
+ impl Meter {
+ pub fn start() -> Meter {
+ Meter(children())
+ }
+
+ pub fn attach(&mut self, _child: &Child) {}
+
+ pub fn stop(self) -> Option<f64> {
+ Some(children()? - self.0?)
+ }
+ }
+}
+
+#[cfg(windows)]
+mod cpu {
+ use std::ffi::c_void;
+ use std::os::windows::io::AsRawHandle;
+ use std::process::Child;
+ use std::ptr::{null, null_mut};
+
+ type Handle = *mut c_void;
+ const JOB_OBJECT_BASIC_ACCOUNTING_INFORMATION: i32 = 1;
+
+ /// JOBOBJECT_BASIC_ACCOUNTING_INFORMATION; times in 100 ns units.
+ #[repr(C)]
+ #[derive(Default)]
+ struct Accounting {
+ total_user_time: i64,
+ total_kernel_time: i64,
+ /// this-period times and process counts, unused
+ _rest: [i64; 4],
+ }
+
+ #[link(name = "kernel32")]
+ unsafe extern "system" {
+ fn CreateJobObjectW(attributes: *mut c_void, name: *const u16) -> Handle;
+ fn AssignProcessToJobObject(job: Handle, process: Handle) -> i32;
+ fn QueryInformationJobObject(job: Handle, class: i32, info: *mut c_void, len: u32, returned: *mut u32) -> i32;
+ fn CloseHandle(handle: Handle) -> i32;
+ }
+
+ /// A job object per run: it adds up the CPU time of every process in it, children included.
+ pub struct Meter {
+ job: Handle,
+ attached: bool,
+ }
+
+ impl Meter {
+ pub fn start() -> Meter {
+ // SAFETY: no security attributes and no name; a null handle means no CPU time.
+ Meter { job: unsafe { CreateJobObjectW(null_mut(), null()) }, attached: false }
+ }
+
+ pub fn attach(&mut self, child: &Child) {
+ if !self.job.is_null() {
+ // SAFETY: both handles are open; the child's lives as long as `child`.
+ self.attached = unsafe { AssignProcessToJobObject(self.job, child.as_raw_handle()) } != 0;
+ }
+ }
+
+ pub fn stop(self) -> Option<f64> {
+ if !self.attached {
+ return None;
+ }
+ let mut info = Accounting::default();
+ // SAFETY: info is a JOBOBJECT_BASIC_ACCOUNTING_INFORMATION of the size we pass.
+ let ok = unsafe {
+ QueryInformationJobObject(
+ self.job,
+ JOB_OBJECT_BASIC_ACCOUNTING_INFORMATION,
+ (&mut info as *mut Accounting).cast(),
+ size_of::<Accounting>() as u32,
+ null_mut(),
+ )
+ } != 0;
+ ok.then(|| (info.total_user_time + info.total_kernel_time) as f64 / 1e7)
+ }
+ }
+
+ impl Drop for Meter {
+ fn drop(&mut self) {
+ if !self.job.is_null() {
+ // SAFETY: the job handle is ours and closed once.
+ unsafe { CloseHandle(self.job) };
+ }
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Side {
+ Original,
+ Control,
+ Rust,
+}
+
+/// Round r runs the three sides rotated left by r, so none of them always goes first.
+fn order(round: usize) -> [Side; 3] {
+ let mut sides = [Side::Original, Side::Control, Side::Rust];
+ sides.rotate_left(round % 3);
+ sides
+}
+
+/// Wall and CPU times per round (indexed by Side) into the numbers bench reports.
+fn summarize(wall: &[[f64; 3]], cpu: &[[Option<f64>; 3]]) -> BenchResult {
+ let (o, c, r) = (Side::Original as usize, Side::Control as usize, Side::Rust as usize);
+ let column = |i: usize| wall.iter().map(|w| w[i]).collect::<Vec<_>>();
+ let change = |i: usize| wall.iter().map(|w| (w[i] / w[o] - 1.0) * 100.0).collect::<Vec<_>>();
+ let (aa, rust) = (Spread::of(&change(c)), Spread::of(&change(r)));
+ let ratio = Spread::of(&wall.iter().map(|w| w[o] / w[r]).collect::<Vec<_>>());
+ let cpu_column = |i: usize| cpu.iter().map(|c| c[i]).collect::<Option<Vec<f64>>>();
+ let (cpu_before, cpu_after) = (cpu_column(o), cpu_column(r));
+ let cpu_speedup = match (&cpu_before, &cpu_after) {
+ (Some(b), Some(a)) if !a.is_empty() && a.iter().all(|&x| x > 0.0) => {
+ Some(Stats::of(&b.iter().zip(a).map(|(b, a)| b / a).collect::<Vec<_>>()).median)
+ }
+ _ => None,
+ };
+ BenchResult {
+ before: Stats::of(&column(o)),
+ after: Stats::of(&column(r)),
+ speedup: ratio.median,
+ speedup_q1: ratio.q1,
+ speedup_q3: ratio.q3,
+ aa,
+ verdict: Some(verdict(&aa, &rust)),
+ cpu_before: cpu_before.map(|x| Stats::of(&x)),
+ cpu_after: cpu_after.map(|x| Stats::of(&x)),
+ cpu_speedup,
+ ..BenchResult::default()
+ }
}
/// The first line that differs between two outputs, if any.
@@ -96,48 +396,45 @@ pub fn first_difference(original: &[u8], rust: &[u8]) -> Option<String> {
}
pub fn run(ctx: &Ctx, runs: usize) -> Result<BenchResult> {
- let (python, args) = ctx.state.lang.bench_command(ctx)?;
- let (python, args) = (python.as_str(), args.as_slice());
+ let (exe, args) = ctx.state.lang.bench_command(ctx)?;
+ let (exe, args) = (exe.as_str(), args.as_slice());
let ports: Vec<String> = ctx.state.ports.values().filter(|p| p.enabled).map(|p| p.id.clone()).collect();
if ports.is_empty() {
ui::warn("no ports are enabled yet, so before and after are the same code");
}
ui::step(format!(
- "timing {} ({runs} runs each, {} vs Rust, interleaved)",
+ "timing {} ({runs} rounds of {} twice and Rust once, rotated)",
ui::bold(ctx.state.command.join(" ")),
ctx.state.lang.label()
));
- // the warm-up runs double as a check that the ports don't change what the app prints
- let (_, original_out) = time_once(ctx, python, args, true)?;
- let (_, rust_out) = time_once(ctx, python, args, false)?;
- let output_diff = first_difference(&original_out, &rust_out);
- let (mut before, mut after) = (Vec::with_capacity(runs), Vec::with_capacity(runs));
- for i in 0..runs {
- if i % 2 == 0 {
- before.push(time_once(ctx, python, args, true)?.0);
- after.push(time_once(ctx, python, args, false)?.0);
- } else {
- after.push(time_once(ctx, python, args, false)?.0);
- before.push(time_once(ctx, python, args, true)?.0);
+ // one uncounted warm-up per side; every later run must print what this first original did
+ let mut check = OutputCheck::new(time_once(ctx, exe, args, true)?.stdout);
+ check.see(false, &time_once(ctx, exe, args, false)?.stdout);
+ let (mut wall, mut cpu) = (Vec::with_capacity(runs), Vec::with_capacity(runs));
+ for round in 0..runs {
+ let (mut w, mut c) = ([0.0; 3], [None; 3]);
+ for side in order(round) {
+ let original = side != Side::Rust;
+ let run = time_once(ctx, exe, args, original)?;
+ check.see(original, &run.stdout);
+ (w[side as usize], c[side as usize]) = (run.wall, run.cpu);
}
+ wall.push(w);
+ cpu.push(c);
}
- let (before, after) = (Stats::of(&before), Stats::of(&after));
- let speedup = if after.median > 0.0 { before.median / after.median } else { 0.0 };
Ok(BenchResult {
lang: ctx.state.lang,
command: ctx.state.command.clone(),
runs,
ports,
- before,
- after,
- speedup,
- output_diff,
+ output_diff: check.diff(),
+ ..summarize(&wall, &cpu)
})
}
#[cfg(test)]
mod tests {
- use super::{Stats, first_difference};
+ use super::*;
#[test]
fn stats() {
@@ -156,4 +453,101 @@ mod tests {
assert_eq!(first_difference(b"a\nb\n", b"a\n").as_deref(), Some(r#"line 2: "b" became "(no line)""#));
assert!(first_difference(b"a\r\n", b"a\n").unwrap().contains("line endings"));
}
+
+ #[test]
+ fn quartiles_match_python() {
+ // statistics.quantiles(xs, n=4)
+ assert_eq!(quartiles(&[5.0, 1.0, 4.0, 2.0, 3.0]), (1.5, 4.5));
+ assert_eq!(quartiles(&[1.0, 2.0, 3.0]), (1.0, 3.0));
+ assert_eq!(quartiles(&[1.0, 2.0, 3.0, 4.0]), (1.25, 3.75));
+ assert_eq!(quartiles(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]), (2.75, 8.25));
+ assert_eq!(quartiles(&[7.0]), (7.0, 7.0));
+ }
+
+ #[test]
+ fn only_changes_beyond_the_aa_band_count() {
+ let s = |q1, q3| Spread { median: (q1 + q3) / 2.0, q1, q3 };
+ let aa = s(-0.5, 2.0);
+ assert_eq!(aa.band(), 2.0);
+ assert_eq!(verdict(&aa, &s(-90.0, -2.1)), Verdict::Faster);
+ assert_eq!(verdict(&aa, &s(-90.0, -2.0)), Verdict::Noise);
+ assert_eq!(verdict(&aa, &s(2.0, 9.0)), Verdict::Noise);
+ assert_eq!(verdict(&aa, &s(2.1, 9.0)), Verdict::Slower);
+ assert_eq!(verdict(&aa, &s(-1.0, 1.0)), Verdict::Noise);
+ assert_eq!(verdict(&s(0.0, 0.0), &s(-1.0, -0.1)), Verdict::Faster);
+ }
+
+ #[test]
+ fn every_side_takes_every_slot() {
+ use Side::*;
+ assert_eq!(order(0), [Original, Control, Rust]);
+ assert_eq!(order(1), [Control, Rust, Original]);
+ assert_eq!(order(2), [Rust, Original, Control]);
+ assert_eq!(order(3), order(0));
+ }
+
+ #[test]
+ fn rounds_are_paired() {
+ // a machine that gets 2x slower halfway: pairing keeps the speedup at 10x
+ let wall = [[1.0, 1.01, 0.1], [2.0, 1.98, 0.2], [2.0, 2.02, 0.2]];
+ let cpu =
+ [[Some(4.0), Some(4.0), Some(1.0)], [Some(8.0), Some(8.0), Some(2.0)], [Some(8.0), Some(8.0), Some(2.0)]];
+ let b = summarize(&wall, &cpu);
+ assert!((b.speedup - 10.0).abs() < 1e-9, "{}", b.speedup);
+ assert!((b.speedup_q1 - 10.0).abs() < 1e-9 && (b.speedup_q3 - 10.0).abs() < 1e-9);
+ assert!((b.aa.band() - 1.0).abs() < 1e-9, "{:?}", b.aa);
+ assert_eq!(b.verdict, Some(Verdict::Faster));
+ assert_eq!(b.cpu_speedup, Some(4.0));
+ assert_eq!(b.cpu_note().as_deref(), Some("CPU time 4.0×"));
+ assert_eq!(b.before.median, 2.0);
+
+ let unknown =
+ [[Some(4.0), Some(4.0), None], [Some(8.0), Some(8.0), Some(2.0)], [Some(8.0), Some(8.0), Some(2.0)]];
+ let b = summarize(&wall, &unknown);
+ assert!(b.cpu_after.is_none() && b.cpu_speedup.is_none() && b.cpu_before.is_some());
+ }
+
+ #[test]
+ fn varying_output_doesnt_blame_the_port() {
+ let mut same = OutputCheck::new(b"a\nb\n".to_vec());
+ for _ in 0..3 {
+ same.see(true, b"a\nb\n");
+ same.see(false, b"a\nb\n");
+ }
+ assert_eq!(same.diff(), None);
+
+ let mut port = OutputCheck::new(b"a\nb\n".to_vec());
+ port.see(true, b"a\nb\n");
+ port.see(false, b"a\nB\n");
+ port.see(false, b"x\nb\n");
+ assert_eq!(port.diff().as_deref(), Some(r#"line 2: "b" became "B""#));
+
+ let mut varies = OutputCheck::new(b"took 1.2s\n".to_vec());
+ varies.see(false, b"took 0.1s\n");
+ varies.see(true, b"took 1.3s\n");
+ assert_eq!(varies.diff().as_deref(), Some(OUTPUT_VARIES));
+ }
+
+ #[test]
+ fn cpu_time_counts_the_child() {
+ if std::env::var_os("FA_TEST_BURN_CPU").is_some() {
+ // fixed work, so the CPU time doesn't depend on how busy the machine is
+ let mut x = 1u64;
+ for _ in 0..100_000_000u64 {
+ x = std::hint::black_box(x.wrapping_mul(6364136223846793005).wrapping_add(1));
+ }
+ return;
+ }
+ let mut cmd = Command::new(std::env::current_exe().unwrap());
+ cmd.args(["--exact", "bench::tests::cpu_time_counts_the_child", "--quiet"])
+ .env("FA_TEST_BURN_CPU", "1")
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+ let (out, cpu) = output_with_cpu(&mut cmd).unwrap();
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
+ assert!(String::from_utf8_lossy(&out.stdout).contains("1 passed"), "{}", String::from_utf8_lossy(&out.stdout));
+ let cpu = cpu.expect("CPU time of the child");
+ assert!(cpu > 0.05, "{cpu}");
+ }
}
diff --git a/src/main.rs b/src/main.rs
index 696960d..448b80b 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -55,7 +55,7 @@ enum Cmd {
/// Agent attempts per function before giving up
#[arg(long, default_value_t = 3)]
attempts: usize,
- /// Benchmark runs
+ /// Benchmark rounds (each runs the original twice and Rust once)
#[arg(long, default_value_t = 5)]
runs: usize,
/// Real calls to record per function
@@ -116,6 +116,7 @@ enum Cmd {
},
/// Time your app with the originals vs the Rust ports
Bench {
+ /// Rounds: each runs the original twice (an A/A control for noise) and Rust once
#[arg(long, default_value_t = 5)]
runs: usize,
},
diff --git a/src/mcp.rs b/src/mcp.rs
index c1455c5..9f9463b 100644
--- a/src/mcp.rs
+++ b/src/mcp.rs
@@ -52,8 +52,8 @@ fn tools() -> Value {
),
tool(
"fast_bench",
- "Time the whole app: original code vs Rust ports.",
- json!({ "runs": { "type": "integer", "default": 5 }, "path": path }),
+ "Time the whole app, original code vs Rust ports, in rounds that run the original twice (an A/A control for noise) and Rust once; wall and CPU time.",
+ json!({ "runs": { "type": "integer", "default": 5, "description": "rounds" }, "path": path }),
json!([])
),
tool(
diff --git a/src/report.rs b/src/report.rs
index 4b5b30d..3a993f3 100644
--- a/src/report.rs
+++ b/src/report.rs
@@ -1,6 +1,6 @@
//! A report worth sharing: markdown for the PR, an SVG card for the README / socials.
-use crate::bench::BenchResult;
+use crate::bench::{BenchResult, Verdict};
use crate::state::{Ctx, Port};
use crate::util::{nanos, secs, times};
use anyhow::{Context, Result};
@@ -30,7 +30,13 @@ fn port_line(p: &Port) -> String {
pub fn svg(project: &str, b: &BenchResult, ports: &[&Port]) -> String {
let headline = times(b.speedup);
let after_w = (300.0 * b.after.median / b.before.median.max(1e-12)).clamp(4.0, 300.0);
- let detail = ports.iter().take(2).map(|p| port_line(p)).collect::<Vec<_>>().join(" ");
+ let mut detail = ports.iter().take(2).map(|p| port_line(p)).collect::<Vec<_>>().join(" ");
+ // the card's detail line holds about 95 characters
+ if let Some(cpu) = b.cpu_note()
+ && detail.chars().count() + cpu.chars().count() + 3 <= 95
+ {
+ detail = if detail.is_empty() { cpu } else { format!("{detail} {cpu}") };
+ }
let sans = "system-ui,-apple-system,Segoe UI,Helvetica,Arial,sans-serif";
let mono = "ui-monospace,SFMono-Regular,Menlo,Consolas,monospace";
format!(
@@ -58,14 +64,44 @@ pub fn svg(project: &str, b: &BenchResult, ports: &[&Port]) -> String {
}
pub fn markdown(project: &str, b: &BenchResult, ports: &[&Port]) -> String {
+ // results saved before rounds and the A/A control have no verdict and no range
+ let how = if b.verdict.is_some() {
+ format!(
+ "median of {} rounds, each running the original twice and Rust once in rotated order; middle half of the rounds {}–{}",
+ b.runs,
+ times(b.speedup_q1).trim_end_matches('×'),
+ times(b.speedup_q3)
+ )
+ } else {
+ format!("median of {} runs each, original and Rust interleaved", b.runs)
+ };
let mut md = format!(
- "# ⚡ {project}: {} faster\n\n`{}` went from **{}** to **{}** (median of {} runs each, original and Rust interleaved).\n\n![fast-anything report](report.svg)\n\n| function | per call | checked against |\n|---|---|---|\n",
+ "# ⚡ {project}: {} faster\n\n`{}` went from **{}** to **{}** ({how}).\n\n",
times(b.speedup),
b.command.join(" "),
secs(b.before.median),
secs(b.after.median),
- b.runs
);
+ if let (Some(before), Some(after), Some(cpu)) = (&b.cpu_before, &b.cpu_after, b.cpu_note()) {
+ md.push_str(&format!(
+ "- {cpu}: **{}** → **{}** (user + system, the app and the processes it waits for)\n",
+ secs(before.median),
+ secs(after.median)
+ ));
+ }
+ // results from before the A/A control have no verdict
+ if let Some(v) = b.verdict {
+ let verdict = match v {
+ Verdict::Faster => "the Rust ports' change is clearly beyond that",
+ Verdict::Slower => "the Rust ports make it slower, beyond that",
+ Verdict::Noise => "the Rust ports' change is within that noise",
+ };
+ md.push_str(&format!(
+ "- A/A control, the original against itself in the same rounds: {:+.1}% (middle half {:+.1}% to {:+.1}%); {verdict}\n",
+ b.aa.median, b.aa.q1, b.aa.q3
+ ));
+ }
+ md.push_str("\n![fast-anything report](report.svg)\n\n| function | per call | checked against |\n|---|---|---|\n");
for p in ports {
let v = p.verify.clone().unwrap_or_default();
let per_call = v
@@ -92,7 +128,7 @@ pub fn write(ctx: &Ctx) -> Result<ReportOut> {
#[cfg(test)]
mod tests {
use super::*;
- use crate::bench::Stats;
+ use crate::bench::{Spread, Stats};
#[test]
fn svg_is_escaped_and_scaled() {
@@ -107,4 +143,36 @@ mod tests {
assert!(card.contains("8.0×"));
assert!(card.contains(r#"width="37.5""#));
}
+
+ #[test]
+ fn report_shows_cpu_time_and_the_aa_control() {
+ let b = BenchResult {
+ command: vec!["python".into(), "app.py".into()],
+ runs: 5,
+ before: Stats { median: 12.0, ..Stats::default() },
+ after: Stats { median: 0.05, ..Stats::default() },
+ speedup: 234.0,
+ speedup_q1: 228.0,
+ speedup_q3: 240.0,
+ aa: Spread { median: 0.7, q1: -0.3, q3: 0.9 },
+ verdict: Some(Verdict::Faster),
+ cpu_before: Some(Stats { median: 11.9, ..Stats::default() }),
+ cpu_after: Some(Stats { median: 0.125, ..Stats::default() }),
+ cpu_speedup: Some(95.2),
+ ..BenchResult::default()
+ };
+ let md = markdown("demo", &b, &[]);
+ assert!(md.contains("median of 5 rounds") && md.contains("228–240×"), "{md}");
+ assert!(md.contains("- CPU time 95×: **11.90s** → **125ms**"), "{md}");
+ assert!(
+ md.contains("+0.7% (middle half -0.3% to +0.9%); the Rust ports' change is clearly beyond that"),
+ "{md}"
+ );
+ let card = svg("demo", &b, &[]);
+ assert!(card.contains("234×") && card.contains("CPU time 95×"));
+
+ let old = BenchResult { speedup: 8.0, ..BenchResult::default() };
+ let md = markdown("demo", &old, &[]);
+ assert!(!md.contains("CPU time") && !md.contains("A/A") && md.contains("interleaved"), "{md}");
+ }
}
diff --git a/src/show.rs b/src/show.rs
index 3451e17..0d4a73e 100644
--- a/src/show.rs
+++ b/src/show.rs
@@ -1,6 +1,6 @@
//! How results look in the terminal.
-use crate::bench::BenchResult;
+use crate::bench::{BenchResult, OUTPUT_VARIES, Verdict};
use crate::pipeline::{PortOut, ScanOut};
use crate::report::ReportOut;
use crate::state::{Ctx, Verify};
@@ -175,16 +175,39 @@ pub fn bench(b: &BenchResult) {
secs(b.after.median)
));
ui::line("");
+ let (word, x, lo, hi) = if b.speedup >= 1.0 {
+ ("faster", b.speedup, b.speedup_q1, b.speedup_q3)
+ } else {
+ ("slower", 1.0 / b.speedup, 1.0 / b.speedup_q3, 1.0 / b.speedup_q1)
+ };
+ let headline = bold(format!("{} {word}", times(x)));
+ let mut detail = format!("median of {} rounds, {}–{}", b.runs, times(lo).trim_end_matches('×'), times(hi));
+ if let Some(cpu) = b.cpu_note() {
+ detail.push_str(&format!("; {cpu}"));
+ }
+ let noise = b.aa.band();
+ detail.push_str(&format!("; A/A ±{noise:.1}%"));
ui::ok(format!(
"{} is {} end to end {}",
bold(cmd),
- rust(bold(format!("{} faster", times(b.speedup)))),
- dim(format!("(median of {}, ±{})", b.runs, secs(b.after.stddev.max(b.before.stddev))))
+ if word == "faster" { rust(headline) } else { red(headline) },
+ dim(format!("({detail})"))
));
- if let Some(diff) = &b.output_diff {
- ui::warn(format!(
- "the app printed something else with the Rust ports ({diff}). Fine if its output varies from run to run; otherwise a port behaves differently from the original"
- ));
+ match b.verdict {
+ Some(Verdict::Noise) => ui::warn(format!(
+ "that's within run-to-run noise: the original alone varies by up to ±{noise:.1}% between runs. More rounds may settle it: fast-anything bench --runs 15"
+ )),
+ Some(Verdict::Slower) => ui::warn(format!(
+ "the app is slower with the Rust ports, beyond its own run-to-run noise (±{noise:.1}%). See which port costs more than it saves: fast-anything status"
+ )),
+ Some(Verdict::Faster) | None => {}
+ }
+ match &b.output_diff {
+ Some(diff) if diff == OUTPUT_VARIES => ui::warn(diff),
+ Some(diff) => ui::warn(format!(
+ "the app printed something else with the Rust ports ({diff}), while every run of the original printed the same: a port behaves differently from the original"
+ )),
+ None => {}
}
}