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.
Rust agent-skillsai-agentsclaude-codeclaude-code-plugincodexdeveloper-toolsffimcpmcp-servernapi-rsnodejsoptimizationperformanceprofilerpyo3pythonrewrite-it-in-rustrubyrusttypescript
scan --calibrate: time the app without the profiler and show the profiler's overhead (#142)
EL4CTEOe7950c99e000
diff --git a/src/bench.rs b/src/bench.rsindex bb9a944..dbfd3cb 100644--- a/src/bench.rs+++ b/src/bench.rs@@ -472,6 +472,14 @@ pub fn first_difference(original: &[u8], rust: &[u8]) -> Option<String> {unreachable!()}+/// The original app's median time over `runs` runs without the profiler: how much a scan's+/// profiled run was slowed down by profiling (#142).+pub fn unprofiled(ctx: &Ctx, runs: usize) -> Result<f64> {+ let (exe, args) = ctx.state.lang.bench_command(ctx)?;+ let walls = (0..runs).map(|_| time_once(ctx, &exe, &args, true).map(|r| r.wall)).collect::<Result<Vec<_>>>()?;+ Ok(Stats::of(&walls).median)+}+pub fn run(ctx: &Ctx, runs: usize) -> Result<BenchResult> {let (exe, args) = ctx.state.lang.bench_command(ctx)?;let (exe, args) = (exe.as_str(), args.as_slice());diff --git a/src/main.rs b/src/main.rsindex 4e8471b..915f189 100644--- a/src/main.rs+++ b/src/main.rs@@ -76,6 +76,9 @@ enum Cmd {/// Stop the app after this many seconds and rank what ran (Python, Node, Go, Java, Kotlin, Ruby, PHP, C, C++, R, C#: servers and GUIs that don't exit)#[arg(long, value_name = "SECS")]duration: Option<f64>,+ /// Also time the app 3 times without the profiler, to show how much profiling slowed it down+ #[arg(long, conflicts_with = "duration")]+ calibrate: bool,/// How you run your app, after --#[arg(last = true, required = true)]command: Vec<String>,@@ -289,8 +292,8 @@ fn run(cmd: Cmd, root: &Path, json: bool) -> Result<()> {Cmd::Go { agent, top, attempts, runs, samples, command } => {pipeline::go(root, command, agent.as_deref(), top, attempts, runs, samples)}- Cmd::Scan { command, duration } => {- let out = pipeline::scan(root, command, duration)?;+ Cmd::Scan { command, duration, calibrate } => {+ let out = pipeline::scan_with(root, command, duration, calibrate)?;if json {show::json(&show::scan_json(&out))} else {diff --git a/src/mcp.rs b/src/mcp.rsindex 0c3e1ec..d3ffca9 100644--- a/src/mcp.rs+++ b/src/mcp.rs@@ -23,7 +23,7 @@ fn tools() -> Value {tool("fast_scan","Run the app under a profiler and rank functions by time share and portability to Rust.",- json!({ "command": { "type": "array", "items": { "type": "string" }, "description": "How the app runs, e.g. [\"python\", \"app.py\"] or [\"go\", \"run\", \".\"]" }, "duration": { "type": "number", "description": "Python, Node, Go, Java, Kotlin, Ruby, PHP, C, C++, R and C#: stop the app after this many seconds (GUIs, servers)" }, "path": path }),+ json!({ "command": { "type": "array", "items": { "type": "string" }, "description": "How the app runs, e.g. [\"python\", \"app.py\"] or [\"go\", \"run\", \".\"]" }, "duration": { "type": "number", "description": "Python, Node, Go, Java, Kotlin, Ruby, PHP, C, C++, R and C#: stop the app after this many seconds (GUIs, servers)" }, "calibrate": { "type": "boolean", "description": "Also time the app 3 times without the profiler and return the profiler's overhead (not with duration)" }, "path": path }),json!(["command"])),tool(@@ -76,7 +76,12 @@ fn call(params: &Value) -> Result<Value> {.as_array().map(|a| a.iter().filter_map(|v| v.as_str().map(String::from)).collect()).unwrap_or_default();- let scan = pipeline::scan(&root, command, args["duration"].as_f64())?;+ let scan = pipeline::scan_with(+ &root,+ command,+ args["duration"].as_f64(),+ args["calibrate"].as_bool() == Some(true),+ )?;let top: Vec<Value> = scan.hotspots.iter()@@ -86,7 +91,7 @@ fn call(params: &Value) -> Result<Value> {"blockers": h.blockers, "warnings": h.warnings, "file": h.file, "line": h.line })}).collect();- json!({ "wall_seconds": scan.wall, "hotspots": top, "notes": scan.notes })+ json!({ "wall_seconds": scan.wall, "unprofiled_seconds": scan.unprofiled, "profiler_overhead": scan.overhead(), "hotspots": top, "notes": scan.notes })}"fast_port" => {let samples = args["samples"].as_u64().unwrap_or(500) as usize;diff --git a/src/pipeline.rs b/src/pipeline.rsindex 12b4354..9658b66 100644--- a/src/pipeline.rs+++ b/src/pipeline.rs@@ -19,14 +19,35 @@ pub struct ScanOut {pub notes: Vec<String>,/// Where what the app printed while it was profiled is kept; None when it printed nothing.pub app_output: Option<PathBuf>,+ /// Median time of the app without the profiler, when the scan was calibrated.+ pub unprofiled: Option<f64>,}+impl ScanOut {+ /// How many times slower the profiled run was than the app on its own.+ pub fn overhead(&self) -> Option<f64> {+ self.unprofiled.filter(|&u| u > 0.0 && self.wall > 0.0).map(|u| self.wall / u)+ }+}++/// Runs of the app without the profiler for scan --calibrate.+pub const CALIBRATION_RUNS: usize = 3;+/// `duration`: stop the app after that many seconds (a GUI or a server that doesn't exit on its own).pub fn scan(root: &Path, command: Vec<String>, duration: Option<f64>) -> Result<ScanOut> {+ scan_with(root, command, duration, false)+}++/// `calibrate`: also time the app without the profiler, so the profiler's overhead is known (#142).+pub fn scan_with(root: &Path, command: Vec<String>, duration: Option<f64>, calibrate: bool) -> Result<ScanOut> {ensure!(!command.is_empty(),"put the command that runs your app after --, e.g. fast-anything scan -- python app.py");+ ensure!(+ !(calibrate && duration.is_some()),+ "--calibrate times the app until it exits, so it can't be used with --duration"+ );let mut ctx = Ctx::open(root)?;let command = match crate::python::unwrap_env_runner(&command, |argv| env_runner_output(&ctx.root, argv))? {Some(unwrapped) => {@@ -73,8 +94,18 @@ pub fn scan(root: &Path, command: Vec<String>, duration: Option<f64>) -> Result<ctx.state.base = profile.base;ctx.state.wall = profile.wall;ctx.state.hotspots = hotspots.clone();+ ctx.state.unprofiled = None;ctx.save()?;- Ok(ScanOut { command, wall: profile.wall, hotspots, notes, app_output })+ let unprofiled = if calibrate {+ ui::step(format!("timing it {CALIBRATION_RUNS} times without the profiler"));+ let u = bench::unprofiled(&ctx, CALIBRATION_RUNS).context("timing the app without the profiler")?;+ ctx.state.unprofiled = Some(u);+ ctx.save()?;+ Some(u)+ } else {+ None+ };+ Ok(ScanOut { command, wall: profile.wall, hotspots, notes, app_output, unprofiled })}/// Keep what the app printed, so a successful scan doesn't swallow it (#142).diff --git a/src/show.rs b/src/show.rsindex 11db3d3..63cdf47 100644--- a/src/show.rs+++ b/src/show.rs@@ -42,7 +42,8 @@ pub fn next(cmd: &str) {}pub fn scan(s: &ScanOut) {- ui::ok(format!("{} ran in {}", bold(s.command.join(" ")), secs(s.wall)));+ ui::ok(format!("{} ran in {} under the profiler", bold(s.command.join(" ")), secs(s.wall)));+ ui::line(format!(" {}", dim(overhead_line(s))));ui::line("");if s.hotspots.is_empty() {ui::line(" No functions from your own code showed up. Is the app doing its work in a library?");@@ -95,6 +96,19 @@ pub fn scan(s: &ScanOut) {}}+/// What the profiler did to the run's time (#142): measured with --calibrate, or a pointer to it.+fn overhead_line(s: &ScanOut) -> String {+ match (s.unprofiled, s.overhead()) {+ (Some(u), Some(x)) => format!(+ "without it the app takes {} (median of {}): the profiler made it {} slower, and shares are of the profiled run",+ secs(u).trim(),+ crate::pipeline::CALIBRATION_RUNS,+ times(x)+ ),+ _ => "times include the profiler's overhead; --calibrate also times the app without it".into(),+ }+}+fn app_output(s: &ScanOut) {if let Some(path) = &s.app_output {ui::line(dim(format!(" what the app printed is in {}", path.display())));@@ -265,7 +279,11 @@ pub fn status(ctx: &Ctx) {next("fast-anything scan -- python your_app.py");return;}- ui::line(format!(" app: {} profiled run: {}", bold(s.command.join(" ")), secs(s.wall)));+ let alone = match s.unprofiled {+ Some(u) => format!(" without the profiler: {}", secs(u)),+ None => String::new(),+ };+ ui::line(format!(" app: {} profiled run: {}{alone}", bold(s.command.join(" ")), secs(s.wall)));if s.ports.is_empty() {ui::line(" Nothing ported yet.");if let Some(h) = s.hotspots.iter().find(|h| h.worth_it()) {@@ -339,6 +357,8 @@ pub fn scan_json(s: &ScanOut) -> Value {"hotspots": hotspots,"notes": s.notes,"app_output": s.app_output,+ "unprofiled_seconds": s.unprofiled,+ "profiler_overhead": s.overhead(),})}@@ -372,6 +392,7 @@ pub fn status_json(ctx: &Ctx) -> Value {"command": s.command,"lang": lang,"wall_seconds": s.wall,+ "unprofiled_seconds": s.unprofiled,"ports": ports,"bench": s.bench,})@@ -451,9 +472,13 @@ mod tests {],notes: vec!["note".into()],app_output: Some(PathBuf::from(".fast/app.log")),+ unprofiled: Some(1.25),};let parsed = parse(scan_json(&scan));assert_eq!(parsed["app_output"], ".fast/app.log");+ assert_eq!(parsed["unprofiled_seconds"], 1.25);+ assert_eq!(parsed["profiler_overhead"], 2.0);+ assert!(overhead_line(&scan).contains("the profiler made it 2.0× slower"), "{}", overhead_line(&scan));assert_eq!(parsed["command"], json!(["python", "app.py"]));assert_eq!(parsed["wall_seconds"], 2.5);assert_eq!(diff --git a/src/state.rs b/src/state.rsindex 6e641c3..eb7909e 100644--- a/src/state.rs+++ b/src/state.rs@@ -26,6 +26,9 @@ pub struct State {/// Folder Python imports the app's modules from, relative to the project.pub base: String,pub wall: f64,+ /// Median time of the app without the profiler, from scan --calibrate.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub unprofiled: Option<f64>,pub hotspots: Vec<Hotspot>,pub ports: BTreeMap<String, Port>,pub bench: Option<BenchResult>,