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, report: show self and total time shares for hot functions
Brixton Pham90b80413685d
diff --git a/src/hotspot.rs b/src/hotspot.rsindex 97cf24c..5ab768f 100644--- a/src/hotspot.rs+++ b/src/hotspot.rs@@ -34,6 +34,8 @@ pub struct Hotspot {pub cumtime: f64,/// Share of the run spent in this function, callees included.pub share: f64,+ /// Share of the run spent in this function's own body, excluding callees.+ pub self_share: f64,/// 0 = can't be ported, 1 = ideal candidate.pub portability: f64,pub score: f64,@@ -63,6 +65,18 @@ impl Hotspot {self.portable() && self.covered_by.is_none() && self.share >= WORTH_IT}+ /// Share of `wall` spent in this function's own body (excludes callees), falling back to+ /// `tottime / wall` for state saved before `self_share` was stored.+ pub fn effective_self_share(&self, wall: f64) -> f64 {+ if self.self_share > 0.0 {+ self.self_share+ } else if wall > 0.0 && self.tottime > 0.0 {+ (self.tottime / wall).clamp(0.0, 1.0)+ } else {+ 0.0+ }+ }+/// Why it isn't worth porting, if it isn't.pub fn why_not(&self) -> Option<String> {if let Some(b) = self.blockers.first() {@@ -205,6 +219,7 @@ pub fn rank(mut list: Vec<Hotspot>, wall: f64) -> Vec<Hotspot> {_ => format!("{}:{}", h.file, h.qualname),};h.share = if wall > 0.0 { (h.cumtime / wall).clamp(0.0, 1.0) } else { 0.0 };+ h.self_share = if wall > 0.0 { (h.tottime / wall).clamp(0.0, 1.0) } else { 0.0 };h.portability = if h.portable() { h.portability.clamp(0.0, 1.0) } else { 0.0 };h.score = h.share * h.portability;}@@ -264,6 +279,25 @@ mod tests {assert!(!ranked[1].worth_it());}+ #[test]+ fn rank_computes_self_and_total_shares() {+ let mut driver = hs("driver", Some("app"), 10.0, 1.0, true);+ driver.tottime = 0.5;+ let mut leaf = hs("leaf", Some("app"), 9.5, 1.0, false);+ leaf.tottime = 9.5;+ let ranked = rank(vec![driver, leaf], 10.0);+ assert_eq!(ranked[0].id, "app.leaf");+ assert!((ranked[0].share - 0.95).abs() < 1e-9);+ assert!((ranked[0].self_share - 0.95).abs() < 1e-9);+ assert_eq!(ranked[1].id, "app.driver");+ assert!((ranked[1].share - 1.0).abs() < 1e-9);+ assert!((ranked[1].self_share - 0.05).abs() < 1e-9);+ assert!((ranked[1].effective_self_share(10.0) - 0.05).abs() < 1e-9);++ let legacy = Hotspot { tottime: 2.5, cumtime: 5.0, share: 0.5, ..Hotspot::default() };+ assert!((legacy.effective_self_share(10.0) - 0.25).abs() < 1e-9);+ }+#[test]fn portable_beats_bigger_but_blocked() {let ranked = rank(@@ -276,6 +310,7 @@ mod tests {);assert_eq!(ranked[0].id, "fuzzy.lev");assert!((ranked[0].share - 0.9).abs() < 1e-9);+ assert_eq!(ranked[0].self_share, 0.0);assert_eq!(ranked[1].id, "fuzzy.norm");assert_eq!(ranked[2].id, "app.py:main");assert_eq!(ranked[2].score, 0.0);diff --git a/src/mcp.rs b/src/mcp.rsindex 9f9463b..74d64ce 100644--- a/src/mcp.rs+++ b/src/mcp.rs@@ -82,7 +82,7 @@ fn call(params: &Value) -> Result<Value> {.iter().take(10).map(|h| {- json!({ "id": h.id, "share": h.share, "calls": h.ncalls, "worth_porting": h.worth_it(), "why_not": h.why_not(),+ json!({ "id": h.id, "share": h.share, "self_share": h.effective_self_share(scan.wall), "calls": h.ncalls, "worth_porting": h.worth_it(), "why_not": h.why_not(),"blockers": h.blockers, "warnings": h.warnings, "file": h.file, "line": h.line })}).collect();diff --git a/src/report.rs b/src/report.rsindex e81f2c8..f0f64cf 100644--- a/src/report.rs+++ b/src/report.rs@@ -136,12 +136,18 @@ fn scan_section(s: &State, b: &BenchResult) -> String {});}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",+ ". Shares are of that profiled run (`total` includes callees; `self` is the function's own body). 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 | total | self | 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));+ md.push_str(&format!(+ "| {} | `{}` | {:.1}% | {:.1}% | {calls} | {outcome} |\n",+ i + 1,+ h.id,+ h.share * 100.0,+ h.effective_self_share(s.wall) * 100.0+ ));}if s.hotspots.len() > TOP {md.push_str(&format!("\n{} more functions from the scan ranked lower.\n", s.hotspots.len() - TOP));@@ -314,21 +320,22 @@ mod tests {#[test]fn report_shows_how_the_ports_were_chosen() {- let hotspot = |id: &str, share: f64, ncalls: u64| Hotspot {+ let hotspot = |id: &str, share: f64, self_share: f64, ncalls: u64| Hotspot {id: id.into(),share,+ self_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),+ Hotspot { blockers: vec!["does I/O: print".into()], ..hotspot("app.main", 0.99, 0.02, 1) },+ hotspot("fuzzy.lev", 0.81, 0.51, 1_250_000),+ Hotspot { covered_by: Some("fuzzy.lev".into()), ..hotspot("fuzzy.cost", 0.3, 0.3, 9_000_000) },+ hotspot("fuzzy.norm", 0.05, 0.05, 2_000),+ hotspot("fuzzy.tiny", 0.004, 0.004, 10),];- hotspots.extend((0..5).map(|i| hotspot(&format!("util.f{i}"), 0.001, 0)));+ hotspots.extend((0..5).map(|i| hotspot(&format!("util.f{i}"), 0.001, 0.001, 0)));let verify = Verify {built: true,total: 500,@@ -379,12 +386,12 @@ mod tests {);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% | - |",+ "| 1 | `app.main` | 99.0% | 2.0% | 1 | does I/O: print |",+ "| 2 | `fuzzy.lev` | 81.0% | 51.0% | 1,250,000 | ported and enabled |",+ "| 3 | `fuzzy.cost` | 30.0% | 30.0% | 9,000,000 | ported inside fuzzy.lev |",+ "| 4 | `fuzzy.norm` | 5.0% | 5.0% | 2,000 | portable, not ported |",+ "| 5 | `fuzzy.tiny` | 0.4% | 0.4% | 10 | too small to matter (0.4% of the run, 2% needed) |",+ "| 6 | `util.f0` | 0.1% | 0.1% | - |",] {assert!(md.contains(row), "{row}\n{md}");}diff --git a/src/show.rs b/src/show.rsindex 04c02f1..52eeae7 100644--- a/src/show.rs+++ b/src/show.rs@@ -50,7 +50,7 @@ pub fn scan(s: &ScanOut) {}return;}- ui::line(dim(format!(" # {} {:<16}{:>11} verdict", pad("function", 30), "time", "calls")));+ ui::line(dim(format!(" # {} {:<16} {:>6}{:>11} verdict", pad("function", 30), "total", "self", "calls")));for (i, h) in s.hotspots.iter().take(10).enumerate() {let verdict = if let Some(by) = &h.covered_by {dim(format!("↳ ported inside {}", by.rsplit(['.', ':']).next().unwrap_or(by)))@@ -62,11 +62,12 @@ pub fn scan(s: &ScanOut) {dim(format!("✗ {}", h.blockers[0]))};let row = format!(- " {:>2} {} {} {:>5.1}%{:>11} {verdict}",+ " {:>2} {} {} {:>5.1}% {:>5.1}%{:>11} {verdict}",i + 1,pad_id(&h.id, 30),rust(bar(h.share, 9)),h.share * 100.0,+ h.effective_self_share(s.wall) * 100.0,if h.ncalls == 0 { "-".to_string() } else { thousands(h.ncalls) });ui::line(if h.worth_it() { row } else { dim(row) });@@ -284,6 +285,7 @@ pub fn scan_json(s: &ScanOut) -> Value {"file": h.file,"line": h.line,"share": h.share,+ "self_share": h.effective_self_share(s.wall),"calls": h.ncalls,"tottime": h.tottime,"cumtime": h.cumtime,@@ -392,7 +394,10 @@ mod tests {file: "fuzzy.py".into(),line: 10,ncalls: 1000,+ tottime: 1.5,+ cumtime: 2.0,share: 0.8,+ self_share: 0.6,..Hotspot::default()},Hotspot {@@ -400,7 +405,10 @@ mod tests {file: "fuzzy.py".into(),line: 30,ncalls: 1,+ tottime: 0.25,+ cumtime: 0.5,share: 0.2,+ self_share: 0.1,blockers: vec!["does I/O".into()],..Hotspot::default()},@@ -410,6 +418,10 @@ mod tests {let parsed = parse(scan_json(&scan));assert_eq!(parsed["command"], json!(["python", "app.py"]));assert_eq!(parsed["wall_seconds"], 2.5);+ assert_eq!(+ (&parsed["hotspots"][0]["self_share"], &parsed["hotspots"][1]["self_share"]),+ (&json!(0.6), &json!(0.1))+ );assert_eq!((&parsed["hotspots"][0]["worth_porting"], &parsed["hotspots"][1]["why_not"]),(&json!(true), &json!("does I/O"))