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.

report: when and where bench ran, and the scan that chose the ports

Milosz5fb86f6e45f6
diff --git a/src/bench.rs b/src/bench.rs
index a690ecd..33a22d0 100644
--- a/src/bench.rs
+++ b/src/bench.rs
@@ -126,6 +126,75 @@ pub struct BenchResult {
/// or OUTPUT_VARIES.
#[serde(skip_serializing_if = "Option::is_none")]
pub output_diff: Option<String>,
+ /// When and on what machine bench ran; results from older versions have none.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub scope: Option<Scope>,
+}
+
+/// When and where a bench ran: a speedup means little without the machine it was measured on.
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(default)]
+pub struct Scope {
+ /// UTC, e.g. "2026-11-26".
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub date: Option<String>,
+ /// As Rust names them: "linux", "macos", "windows"; "x86_64", "aarch64".
+ pub os: String,
+ pub arch: String,
+ /// Logical CPUs.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub cpus: Option<usize>,
+ /// The CPU's model name, where the OS tells it cheaply.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub cpu: Option<String>,
+}
+
+impl Scope {
+ pub fn here() -> Scope {
+ Scope {
+ date: util::today(),
+ os: std::env::consts::OS.into(),
+ arch: std::env::consts::ARCH.into(),
+ cpus: std::thread::available_parallelism().ok().map(|n| n.get()),
+ cpu: cpu_model(),
+ }
+ }
+}
+
+/// The CPU's model name; None where it isn't cheap to get.
+fn cpu_model() -> Option<String> {
+ let found = if cfg!(target_os = "linux") {
+ std::fs::read_to_string("/proc/cpuinfo").ok().and_then(|t| cpuinfo_model(&t))
+ } else if cfg!(target_os = "macos") {
+ printed("sysctl", &["-n", "machdep.cpu.brand_string"])
+ } else if cfg!(windows) {
+ let key = r"HKLM\HARDWARE\DESCRIPTION\System\CentralProcessor\0";
+ printed("reg", &["query", key, "/v", "ProcessorNameString"])
+ .and_then(|t| registry_value(&t))
+ .or_else(|| std::env::var("PROCESSOR_IDENTIFIER").ok())
+ } else {
+ None
+ };
+ found.map(|m| m.split_whitespace().collect::<Vec<_>>().join(" ")).filter(|m| !m.is_empty())
+}
+
+/// What a command prints, if it starts and succeeds.
+fn printed(program: &str, args: &[&str]) -> Option<String> {
+ let out = Command::new(program).args(args).stdin(Stdio::null()).stderr(Stdio::null()).output().ok()?;
+ out.status.success().then(|| String::from_utf8_lossy(&out.stdout).into_owned())
+}
+
+/// The first `model name` in /proc/cpuinfo (ARM kernels may have none).
+fn cpuinfo_model(text: &str) -> Option<String> {
+ text.lines().find_map(|l| {
+ let (key, value) = l.split_once(':')?;
+ (key.trim() == "model name").then(|| value.trim().to_string())
+ })
+}
+
+/// The data in `reg query` output: ` ProcessorNameString REG_SZ Intel(R) Core(TM) i7-8700 CPU @ 3.20GHz`.
+fn registry_value(text: &str) -> Option<String> {
+ text.lines().find_map(|l| l.split_once("REG_SZ").map(|(_, v)| v.trim().to_string()))
}
impl BenchResult {
@@ -429,6 +498,7 @@ pub fn run(ctx: &Ctx, runs: usize) -> Result<BenchResult> {
runs,
ports,
output_diff: check.diff(),
+ scope: Some(Scope::here()),
..summarize(&wall, &cpu)
})
}
@@ -529,6 +599,17 @@ mod tests {
assert_eq!(varies.diff().as_deref(), Some(OUTPUT_VARIES));
}
+ #[test]
+ fn the_machine_is_named_when_it_tells() {
+ let cpuinfo = "processor\t: 0\nvendor_id\t: AuthenticAMD\nmodel name\t: AMD Ryzen 5 PRO 4650GE with Radeon Graphics\nflags\t\t: fpu\n\nprocessor\t: 1\nmodel name\t: other\n";
+ assert_eq!(cpuinfo_model(cpuinfo).as_deref(), Some("AMD Ryzen 5 PRO 4650GE with Radeon Graphics"));
+ assert_eq!(cpuinfo_model("processor\t: 0\nBogoMIPS\t: 48.00\n"), None);
+ let reg = "\r\nHKEY_LOCAL_MACHINE\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0\r\n ProcessorNameString REG_SZ Intel(R) Core(TM) i7-8700 CPU @ 3.20GHz\r\n\r\n";
+ assert_eq!(registry_value(reg).as_deref(), Some("Intel(R) Core(TM) i7-8700 CPU @ 3.20GHz"));
+ let here = Scope::here();
+ assert!(here.date.is_some() && !here.os.is_empty() && here.cpus.is_some_and(|n| n > 0), "{here:?}");
+ }
+
#[test]
fn cpu_time_counts_the_child() {
if std::env::var_os("FA_TEST_BURN_CPU").is_some() {
diff --git a/src/report.rs b/src/report.rs
index 6f806fc..e81f2c8 100644
--- a/src/report.rs
+++ b/src/report.rs
@@ -1,8 +1,9 @@
//! A report worth sharing: markdown for the PR, an SVG card for the README / socials.
-use crate::bench::{BenchResult, Verdict};
-use crate::state::{Ctx, Port};
-use crate::util::{nanos, secs, times};
+use crate::bench::{BenchResult, Scope, Verdict};
+use crate::hotspot::Hotspot;
+use crate::state::{Ctx, Port, State};
+use crate::util::{nanos, secs, thousands, times};
use anyhow::{Context, Result};
use serde::Serialize;
use std::fs;
@@ -68,7 +69,92 @@ pub fn svg(project: &str, b: &BenchResult, ports: &[&Port]) -> String {
)
}
-pub fn markdown(project: &str, b: &BenchResult, ports: &[&Port]) -> String {
+/// "Measured 2026-11-26 on AMD Ryzen 5 PRO 4650GE (12 logical CPUs), Linux x86_64.", leaving out what
+/// isn't known; None when nothing is.
+fn scope_line(s: &Scope) -> Option<String> {
+ let cpus = s.cpus.map(|n| format!("{n} logical CPU{}", if n == 1 { "" } else { "s" }));
+ let machine = match (&s.cpu, cpus) {
+ (Some(model), Some(cpus)) => Some(format!("{model} ({cpus})")),
+ (model, cpus) => model.clone().or(cpus),
+ };
+ let os = match s.os.as_str() {
+ "linux" => "Linux",
+ "macos" => "macOS",
+ "windows" => "Windows",
+ "freebsd" => "FreeBSD",
+ os => os,
+ };
+ let platform = format!("{os} {}", s.arch).trim().to_string();
+ let on: Vec<String> = machine.into_iter().chain(Some(platform).filter(|p| !p.is_empty())).collect();
+ if s.date.is_none() && on.is_empty() {
+ return None;
+ }
+ let date = s.date.as_ref().map(|d| format!(" {d}")).unwrap_or_default();
+ let on = if on.is_empty() { String::new() } else { format!(" on {}", on.join(", ")) };
+ Some(format!("Measured{date}{on}."))
+}
+
+/// How many of the last scan's functions the report lists.
+const TOP: usize = 8;
+
+/// What became of a function from the scan, in the words `status` and `scan` use.
+fn outcome(h: &Hotspot, s: &State) -> String {
+ match s.ports.get(&h.id) {
+ Some(p) => match &p.verify {
+ _ if p.enabled => "ported and enabled".into(),
+ Some(v) if v.ok() => "ported and verified, not enabled".into(),
+ Some(v) if !v.built => "ported, doesn't compile".into(),
+ Some(_) => "ported, doesn't match the original".into(),
+ None => "ported, waiting for the Rust".into(),
+ },
+ None if h.worth_it() => "portable, not ported".into(),
+ None => h.why_not().unwrap_or_default(),
+ }
+}
+
+/// How the ports were chosen: the last scan's top functions and how much the profiler slowed the app.
+/// Empty without scan data.
+fn scan_section(s: &State, b: &BenchResult) -> String {
+ if s.hotspots.is_empty() {
+ return String::new();
+ }
+ let mut md = format!(
+ "\n## How the ports were chosen\n\nThe last scan profiled `{}`, which took **{}** under the profiler",
+ s.command.join(" "),
+ secs(s.wall)
+ );
+ let (wall, original) = (s.wall, b.before.median);
+ if wall > 0.0 && original > 0.0 {
+ md.push_str(&if wall >= original {
+ format!(
+ " against **{}** without it (the original's median above): profiling made it run {} as long",
+ secs(original),
+ times(wall / original)
+ )
+ } else {
+ format!(", less than the original's **{}** median above: the scan was likely stopped early", secs(original))
+ });
+ }
+ md.push_str(
+ ". Shares are of that profiled run and count each function's callees too. They are not direct ratios: the profiler slows some code more than the rest, so a share isn't the part of the original's time a port can save.\n\n| # | function | share of the profiled run | calls | outcome |\n|---|---|---|---|---|\n",
+ );
+ for (i, h) in s.hotspots.iter().take(TOP).enumerate() {
+ let calls = if h.ncalls == 0 { "-".to_string() } else { thousands(h.ncalls) };
+ let outcome = outcome(h, s).replace('|', "\\|").replace('\n', " ");
+ md.push_str(&format!("| {} | `{}` | {:.1}% | {calls} | {outcome} |\n", i + 1, h.id, h.share * 100.0));
+ }
+ if s.hotspots.len() > TOP {
+ md.push_str(&format!("\n{} more functions from the scan ranked lower.\n", s.hotspots.len() - TOP));
+ }
+ md
+}
+
+fn enabled(s: &State) -> Vec<&Port> {
+ s.ports.values().filter(|p| p.enabled).collect()
+}
+
+/// The report for the last bench `b`; `s` holds the ports and the scan that chose them.
+pub fn markdown(project: &str, b: &BenchResult, s: &State) -> String {
// results saved before rounds and the A/A control have no verdict and no range
let how = if b.verdict.is_some() {
format!(
@@ -81,8 +167,9 @@ pub fn markdown(project: &str, b: &BenchResult, ports: &[&Port]) -> String {
format!("median of {} runs each, original and Rust interleaved", b.runs)
};
let (head, word) = headline(b.speedup);
+ let scope = b.scope.as_ref().and_then(scope_line).map(|l| format!("{l}\n\n")).unwrap_or_default();
let mut md = format!(
- "# ⚡ {project}: {head} {word}\n\n`{}` went from **{}** to **{}** ({how}).\n\n",
+ "# ⚡ {project}: {head} {word}\n\n{scope}`{}` went from **{}** to **{}** ({how}).\n\n",
b.command.join(" "),
secs(b.before.median),
secs(b.after.median),
@@ -107,7 +194,7 @@ pub fn markdown(project: &str, b: &BenchResult, ports: &[&Port]) -> String {
));
}
md.push_str("\n![fast-anything report](report.svg)\n\n| function | per call | checked against |\n|---|---|---|\n");
- for p in ports {
+ for p in enabled(s) {
let v = p.verify.clone().unwrap_or_default();
let per_call = v
.micro
@@ -115,6 +202,7 @@ pub fn markdown(project: &str, b: &BenchResult, ports: &[&Port]) -> String {
.unwrap_or_else(|| "n/a".into());
md.push_str(&format!("| `{}` | {per_call} | {}/{} recorded real calls |\n", p.id, v.passed, v.total));
}
+ md.push_str(&scan_section(s, b));
md.push_str("\nThe original code stays in place: set `FAST_ANYTHING_DISABLE=1` to run it, or `fast-anything disable <id>` to remove the switch.\n\n<sub>Made with [fast-anything](https://github.com/EL4CTEO/fast-anything)</sub>\n");
md
}
@@ -122,8 +210,8 @@ pub fn markdown(project: &str, b: &BenchResult, ports: &[&Port]) -> String {
pub fn write(ctx: &Ctx) -> Result<ReportOut> {
let b = ctx.state.bench.as_ref().context("no benchmark yet: run fast-anything bench")?;
let project = ctx.root.file_name().map(|s| s.to_string_lossy().into_owned()).unwrap_or_else(|| "your app".into());
- let ports: Vec<&Port> = ctx.state.ports.values().filter(|p| p.enabled).collect();
- let text = markdown(&project, b, &ports);
+ let ports = enabled(&ctx.state);
+ let text = markdown(&project, b, &ctx.state);
let (md_path, svg_path) = (ctx.fast.join("report.md"), ctx.fast.join("report.svg"));
fs::write(&md_path, &text)?;
fs::write(&svg_path, svg(&project, b, &ports))?;
@@ -134,6 +222,7 @@ pub fn write(ctx: &Ctx) -> Result<ReportOut> {
mod tests {
use super::*;
use crate::bench::{Spread, Stats};
+ use crate::state::Verify;
#[test]
fn svg_is_escaped_and_scaled() {
@@ -157,7 +246,7 @@ mod tests {
speedup: 8.42 / 9.27,
..BenchResult::default()
};
- let (md, card) = (markdown("app", &b, &[]), svg("app", &b, &[]));
+ let (md, card) = (markdown("app", &b, &State::default()), svg("app", &b, &[]));
assert!(md.starts_with("# ⚡ app: 1.1× slower"), "{md}");
assert!(card.contains(">slower</tspan>") && !card.contains("faster"), "{card}");
}
@@ -179,7 +268,7 @@ mod tests {
cpu_speedup: Some(95.2),
..BenchResult::default()
};
- let md = markdown("demo", &b, &[]);
+ let md = markdown("demo", &b, &State::default());
assert!(md.contains("median of 5 rounds") && md.contains("228–240×"), "{md}");
assert!(md.contains("- CPU time 95×: **11.90s** → **125ms**"), "{md}");
assert!(
@@ -190,7 +279,124 @@ mod tests {
assert!(card.contains("234×") && card.contains("CPU time 95×"));
let old = BenchResult { speedup: 8.0, ..BenchResult::default() };
- let md = markdown("demo", &old, &[]);
+ let md = markdown("demo", &old, &State::default());
assert!(!md.contains("CPU time") && !md.contains("A/A") && md.contains("interleaved"), "{md}");
}
+
+ #[test]
+ fn report_says_when_and_where_it_was_measured() {
+ let scope = Scope {
+ date: Some("2026-11-26".into()),
+ os: "linux".into(),
+ arch: "x86_64".into(),
+ cpus: Some(12),
+ cpu: Some("AMD Ryzen 5 PRO 4650GE".into()),
+ };
+ let b = BenchResult { speedup: 8.0, scope: Some(scope.clone()), ..BenchResult::default() };
+ let md = markdown("app", &b, &State::default());
+ assert!(
+ md.starts_with(
+ "# ⚡ app: 8.0× faster\n\nMeasured 2026-11-26 on AMD Ryzen 5 PRO 4650GE (12 logical CPUs), Linux x86_64.\n\n`"
+ ),
+ "{md}"
+ );
+ let unknown_cpu = Scope { os: "windows".into(), cpu: None, cpus: Some(1), ..scope };
+ assert_eq!(scope_line(&unknown_cpu).as_deref(), Some("Measured 2026-11-26 on 1 logical CPU, Windows x86_64."));
+ assert_eq!(scope_line(&Scope::default()), None);
+
+ // a result saved before bench recorded its scope
+ let old: BenchResult =
+ serde_json::from_str(r#"{"runs": 5, "before": {"median": 4.0}, "speedup": 8.0}"#).unwrap();
+ assert!(old.scope.is_none());
+ let md = markdown("app", &old, &State::default());
+ assert!(md.starts_with("# ⚡ app: 8.0× faster\n\n`") && !md.contains("Measured"), "{md}");
+ }
+
+ #[test]
+ fn report_shows_how_the_ports_were_chosen() {
+ let hotspot = |id: &str, share: f64, ncalls: u64| Hotspot {
+ id: id.into(),
+ share,
+ ncalls,
+ portability: 0.9,
+ ..Hotspot::default()
+ };
+ let mut hotspots = vec![
+ Hotspot { blockers: vec!["does I/O: print".into()], ..hotspot("app.main", 0.99, 1) },
+ hotspot("fuzzy.lev", 0.81, 1_250_000),
+ Hotspot { covered_by: Some("fuzzy.lev".into()), ..hotspot("fuzzy.cost", 0.3, 9_000_000) },
+ hotspot("fuzzy.norm", 0.05, 2_000),
+ hotspot("fuzzy.tiny", 0.004, 10),
+ ];
+ hotspots.extend((0..5).map(|i| hotspot(&format!("util.f{i}"), 0.001, 0)));
+ let verify = Verify {
+ built: true,
+ total: 500,
+ passed: 500,
+ micro: serde_json::from_str(r#"{"original_ns": 9000.0, "rust_ns": 300.0, "speedup": 30.0}"#).unwrap(),
+ ..Verify::default()
+ };
+ let port = Port {
+ id: "fuzzy.lev".into(),
+ file: "fuzzy.py".into(),
+ module: "fuzzy".into(),
+ func: "lev".into(),
+ ext: "fa_fuzzy_lev".into(),
+ crate_dir: ".fast/ports/fuzzy.lev".into(),
+ recorded: 500,
+ calls_seen: 1_250_000,
+ verify: Some(verify),
+ enabled: true,
+ lang: Default::default(),
+ owner: None,
+ line: 1,
+ sources: vec![],
+ };
+ let s = State {
+ command: vec!["python".into(), "app.py".into()],
+ wall: 12.4,
+ hotspots,
+ ports: [("fuzzy.lev".to_string(), port)].into(),
+ ..State::default()
+ };
+ let b = BenchResult {
+ command: s.command.clone(),
+ before: Stats { median: 4.0, ..Stats::default() },
+ after: Stats { median: 0.5, ..Stats::default() },
+ speedup: 8.0,
+ ..BenchResult::default()
+ };
+ let md = markdown("app", &b, &s);
+ let (table, section, stays) = (
+ md.find("| `fuzzy.lev` | **30×**").unwrap(),
+ md.find("## How the ports were chosen").unwrap(),
+ md.find("The original code stays in place").unwrap(),
+ );
+ assert!(table < section && section < stays, "after the ports' table: {md}");
+ assert!(
+ md.contains("`python app.py`, which took **12.40s** under the profiler against **4.00s** without it (the original's median above): profiling made it run 3.1× as long."),
+ "{md}"
+ );
+ assert!(md.contains("They are not direct ratios"), "{md}");
+ for row in [
+ "| 1 | `app.main` | 99.0% | 1 | does I/O: print |",
+ "| 2 | `fuzzy.lev` | 81.0% | 1,250,000 | ported and enabled |",
+ "| 3 | `fuzzy.cost` | 30.0% | 9,000,000 | ported inside fuzzy.lev |",
+ "| 4 | `fuzzy.norm` | 5.0% | 2,000 | portable, not ported |",
+ "| 5 | `fuzzy.tiny` | 0.4% | 10 | too small to matter (0.4% of the run, 2% needed) |",
+ "| 6 | `util.f0` | 0.1% | - |",
+ ] {
+ assert!(md.contains(row), "{row}\n{md}");
+ }
+ assert!(md.contains("| 8 | `util.f2`") && !md.contains("`util.f3`"), "{md}");
+ assert!(md.contains("2 more functions from the scan ranked lower."), "{md}");
+
+ let stopped_early = State { wall: 2.0, ..s.clone() };
+ let md = markdown("app", &b, &stopped_early);
+ assert!(md.contains("less than the original's **4.00s** median above") && !md.contains("as long"), "{md}");
+
+ let no_scan = State { hotspots: vec![], ..s };
+ let md = markdown("app", &b, &no_scan);
+ assert!(!md.contains("How the ports were chosen") && md.contains("| `fuzzy.lev` |"), "{md}");
+ }
}
diff --git a/src/util.rs b/src/util.rs
index efac7f7..bd37802 100644
--- a/src/util.rs
+++ b/src/util.rs
@@ -172,6 +172,25 @@ pub fn thousands(n: u64) -> String {
out
}
+/// Year, month and day of a day counted from 1970-01-01 (proleptic Gregorian calendar).
+pub fn civil_date(days: i64) -> (i64, u32, u32) {
+ // years run March to February here, so the leap day comes last
+ let z = days + 719_468;
+ let (era, doe) = (z.div_euclid(146_097), z.rem_euclid(146_097));
+ let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
+ let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
+ let mp = (5 * doy + 2) / 153;
+ let (day, month) = (doy - (153 * mp + 2) / 5 + 1, if mp < 10 { mp + 3 } else { mp - 9 });
+ (yoe + era * 400 + i64::from(month <= 2), month as u32, day as u32)
+}
+
+/// Today's date in UTC, e.g. "2026-11-26"; None if the clock is before 1970.
+pub fn today() -> Option<String> {
+ let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).ok()?.as_secs();
+ let (y, m, d) = civil_date((secs / 86_400) as i64);
+ Some(format!("{y:04}-{m:02}-{d:02}"))
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -193,4 +212,18 @@ mod tests {
assert_eq!(nanos(350.0), "350ns");
assert_eq!(secs(0.25), "250ms");
}
+
+ #[test]
+ fn days_since_1970_become_dates() {
+ assert_eq!(civil_date(0), (1970, 1, 1));
+ assert_eq!(civil_date(10_956), (1999, 12, 31));
+ assert_eq!(civil_date(11_016), (2000, 2, 29), "a leap day in a year divisible by 400");
+ assert_eq!(civil_date(19_782), (2024, 2, 29));
+ assert_eq!(civil_date(19_783), (2024, 3, 1));
+ assert_eq!(civil_date(20_783), (2026, 11, 26));
+ assert_eq!((civil_date(47_540), civil_date(47_541)), ((2100, 2, 28), (2100, 3, 1)), "2100 has no leap day");
+ assert_eq!(civil_date(-1), (1969, 12, 31));
+ let today = today().unwrap();
+ assert!(today.len() == 10 && today.starts_with("20"), "{today}");
+ }
}