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 --duration for C and C++ apps
Mohit Mishra0f8e3da73ecd
diff --git a/README.md b/README.mdindex 080fbbf..49bd594 100644--- a/README.md+++ b/README.md@@ -105,7 +105,7 @@ Or wire it up by hand:| Kotlin/JVM (Gradle, `src/main/kotlin`, JDK 22+) | the Java bridge; top-level functions, `object` and companion members, extension functions | ✅ || Go 1.22+ (`go run .`) | the same C bridge, through the Windows loader or dlopen (cgo); servers: `scan --duration 30` | ✅ || PHP 8.1+ (`php app.php`) | the same C bridge, through PHP's FFI extension (`extension=ffi`); servers: `scan --duration 30` (with `pcntl`) | ✅ |-| C and C++ (gcc, clang or Intel oneAPI icx/icpx: `clang -O2 main.c lib.c`) | the same C bridge, through LoadLibrary or dlopen | ✅ |+| C and C++ (gcc, clang or Intel oneAPI icx/icpx: `clang -O2 main.c lib.c`) | the same C bridge, through LoadLibrary or dlopen; servers: `scan --duration 30` | ✅ || C# / .NET 8+ (`dotnet run -c Release`) | the same C bridge, through NativeLibrary; profiled with EventPipe, nothing to install; GUIs and servers: `scan --duration 30` | ✅ || R 4.0+ (`Rscript app.R`) | the same C bridge, through base R's `.C()`; profiled with Rprof, no packages or R headers needed | ✅ |diff --git a/src/backend.rs b/src/backend.rsindex 00ead4d..d935414 100644--- a/src/backend.rs+++ b/src/backend.rs@@ -141,7 +141,7 @@ impl Lang {/// Whether `scan --duration` can stop this language's apps.pub fn stops_after_duration(self) -> bool {- matches!(self, Lang::Python | Lang::Node | Lang::Go | Lang::Java | Lang::Kotlin | Lang::Ruby | Lang::Php | Lang::CSharp)+ matches!(self, Lang::Python | Lang::Node | Lang::Go | Lang::Java | Lang::Kotlin | Lang::Ruby | Lang::Php | Lang::C | Lang::Cpp | Lang::CSharp)}/// `duration` (see stops_after_duration): stop the app after that many seconds.@@ -153,7 +153,7 @@ impl Lang {Lang::Java => java::profile(ctx, exe, args, duration),Lang::Go => golang::profile(ctx, exe, args, duration),Lang::Php => php::profile(ctx, exe, args, duration),- Lang::C | Lang::Cpp => cfamily::profile(ctx, exe, args, self),+ Lang::C | Lang::Cpp => cfamily::profile(ctx, exe, args, self, duration),Lang::CSharp => csharp::profile(ctx, exe, args, duration),Lang::R => r::profile(ctx, exe, args),Lang::Kotlin => kotlin::profile(ctx, exe, args, duration),diff --git a/src/cfamily.rs b/src/cfamily.rsindex be57fb7..a2f2de0 100644--- a/src/cfamily.rs+++ b/src/cfamily.rs@@ -15,6 +15,7 @@ use std::collections::BTreeMap;use std::fs;use std::path::{Path, PathBuf};use std::process::{Command, Stdio};+use std::time::Duration;const PROF_H: &str = include_str!("cfamily/prof.h");const PROF_C: &str = include_str!("cfamily/prof.c");@@ -156,7 +157,22 @@ fn errors_first(log: &str) -> String {}fn run(ctx: &Ctx, bin: &Path, b: &Build, env: &[(&str, &Path)], derive: bool) -> Result<std::process::Output> {+ Ok(run_for(ctx, bin, b, env, derive, None)?.0)+}++/// run, ending the app after `duration` seconds (and stopping it from outside 15s later).+fn run_for(+ ctx: &Ctx,+ bin: &Path,+ b: &Build,+ env: &[(&str, &Path)],+ derive: bool,+ duration: Option<f64>,+) -> Result<(std::process::Output, bool)> {let mut cmd = Command::new(bin);+ if let Some(d) = duration {+ cmd.env("FAST_ANYTHING_STOP_AFTER_MS", ((d * 1000.0) as u64).to_string());+ }cmd.args(&b.args).current_dir(&ctx.root).env(DISABLE_ENV, "1").stdin(Stdio::null());for (k, v) in env {cmd.env(k, v);@@ -164,7 +180,12 @@ fn run(ctx: &Ctx, bin: &Path, b: &Build, env: &[(&str, &Path)], derive: bool) ->if !derive {cmd.env("FAST_ANYTHING_RECORD_DERIVE", "0");}- output(&mut cmd, "the app")+ util::output_for(+ &mut cmd,+ "the app",+ duration.map(|d| Duration::from_secs_f64(d.ceil() + 15.0)),+ Duration::from_secs(10),+ )}pub fn bench_command(ctx: &Ctx, cc: &str) -> Result<(String, Vec<String>)> {@@ -849,7 +870,8 @@ fn runtime_source(dir: &Path, name: &str, text: &str, lang: Lang) -> Result<PathOk(path)}-pub fn profile(ctx: &Ctx, cc: &str, args: &[String], lang: Lang) -> Result<Profile> {+/// `duration`: end the app after that many seconds (servers that run until closed).+pub fn profile(ctx: &Ctx, cc: &str, args: &[String], lang: Lang, duration: Option<f64>) -> Result<Profile> {let b = Build::parse(args)?;let found = describe(ctx, &b, lang)?;let dir = runtime_dir(ctx)?;@@ -868,7 +890,8 @@ pub fn profile(ctx: &Ctx, cc: &str, args: &[String], lang: Lang) -> Result<Profilet bin = bin?;let out = ctx.fast.join("profile.json");let _ = fs::remove_file(&out);- let ran = run(ctx, &bin, &b, &[("FAST_ANYTHING_PROF_OUT", &out)], true)?;+ let (ran, killed) = run_for(ctx, &bin, &b, &[("FAST_ANYTHING_PROF_OUT", &out)], true, duration)?;+ ensure!(!killed, "the app was still running 15s after --duration");ensure!(ran.status.success(), "the app failed ({}):\n{}", ran.status, tail(&combined(&ran), 30));let result: Value = serde_json::from_str(&fs::read_to_string(&out).context("the profiler wrote nothing: does main return normally?")?,@@ -1423,6 +1446,28 @@ mod tests {}}+ #[test]+ fn duration_ends_an_app_that_runs_until_closed() {+ let Some(cc) = ["cc", "gcc", "clang"].into_iter().find(|c| Command::new(c).arg("--version").output().is_ok())+ else {+ eprintln!("no C compiler on PATH, skipping");+ return;+ };+ let dir = std::env::temp_dir().join(format!("fa-c-duration-test-{}", std::process::id()));+ fs::create_dir_all(&dir).unwrap();+ // a server's shape: work, forever+ let main = "long work(long n) {\n long s = 0;\n for (long i = 0; i < n; i++) s += i * i % 7;\n return s;\n}\n\nint main(void) {\n volatile long sink = 0;\n for (;;) sink += work(20000000);\n}\n";+ fs::write(dir.join("main.c"), main).unwrap();+ let ctx = Ctx::open(&dir).unwrap();+ let p = profile(&ctx, cc, &["-O1".into(), "main.c".into()], Lang::C, Some(1.0));+ let after = fs::read_to_string(dir.join("main.c")).unwrap();+ let _ = fs::remove_dir_all(&dir);+ let p = p.unwrap();+ assert!(p.functions.iter().any(|f| f.name == "work" && f.ncalls > 0), "{:?}", p.functions);+ assert!((0.9..10.0).contains(&p.wall), "{}", p.wall);+ assert_eq!(after, main);+ }+#[test]fn finds_c_and_cpp_functions() {let c = "#include <stdio.h>\n/* a { comment */\nstatic int lev(const char *a, const char *b) {\n return 0;\n}\n\nlong count(const int *xs, size_t n, int max)\n{\n if (n) { return 1; }\n printf(\"{\");\n return 0;\n}\nint main(void) { return lev(\"a\", \"b\"); }\n";diff --git a/src/cfamily/prof.c b/src/cfamily/prof.cindex d88dda8..ab890e8 100644--- a/src/cfamily/prof.c+++ b/src/cfamily/prof.c@@ -4,6 +4,15 @@#endif#include <stdio.h>#include <stdlib.h>+#ifdef _WIN32+#ifndef WIN32_LEAN_AND_MEAN+#define WIN32_LEAN_AND_MEAN+#endif+#include <windows.h>+#else+#include <signal.h>+#include <unistd.h>+#endif#include "fa_clock.h"#include "fa_prof.h"@@ -58,7 +67,31 @@ static void fa_prof_save(void) {fclose(out);}+/* scan --duration: a server runs until closed, so end it after that long; exit() writes the profile+ * (atexit above). If the app is stuck where exit can't run, scan stops it from outside. */+#ifdef _WIN32+static DWORD WINAPI fa_prof_stop(LPVOID ms) {+ Sleep((DWORD) (size_t) ms);+ exit(0);+}+#else+static void fa_prof_stop(int sig) {+ (void) sig;+ exit(0);+}+#endif+__attribute__((constructor)) static void fa_prof_start(void) {fa_started = fa_now();atexit(fa_prof_save);+ const char *stop = getenv("FAST_ANYTHING_STOP_AFTER_MS");+ long ms = stop ? atol(stop) : 0;+ if (ms > 0) {+#ifdef _WIN32+ CreateThread(NULL, 0, fa_prof_stop, (LPVOID) (size_t) ms, 0, NULL);+#else+ signal(SIGALRM, fa_prof_stop);+ alarm((unsigned) ((ms + 999) / 1000));+#endif+ }}diff --git a/src/main.rs b/src/main.rsindex 54d6e6d..0068ad1 100644--- a/src/main.rs+++ b/src/main.rs@@ -67,7 +67,7 @@ enum Cmd {},/// Run your app under a profiler and rank what's worth portingScan {- /// Stop the app after this many seconds and rank what ran (Python, Node, Go, Java, Kotlin, Ruby, PHP, C#: servers and GUIs that don't exit)+ /// Stop the app after this many seconds and rank what ran (Python, Node, Go, Java, Kotlin, Ruby, PHP, C, C++, C#: servers and GUIs that don't exit)#[arg(long, value_name = "SECS")]duration: Option<f64>,/// How you run your app, after --diff --git a/src/mcp.rs b/src/mcp.rsindex 0e25da2..5ee131f 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 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++ and C#: stop the app after this many seconds (GUIs, servers)" }, "path": path }),json!(["command"])),tool(diff --git a/src/pipeline.rs b/src/pipeline.rsindex 516ab58..d751fa3 100644--- a/src/pipeline.rs+++ b/src/pipeline.rs@@ -36,7 +36,7 @@ pub fn scan(root: &Path, command: Vec<String>, duration: Option<f64>) -> Result<let lang = crate::cfamily::refine(Lang::detect(&command[0])?, &command[1..]);let lang = crate::kotlin::refine(lang, &command[0], &ctx.root);if let Some(d) = duration {- ensure!(lang.stops_after_duration(), "--duration works for Python, JavaScript/TypeScript, Go, Java, Kotlin, Ruby, PHP and C# apps only so far");+ ensure!(lang.stops_after_duration(), "--duration works for Python, JavaScript/TypeScript, Go, Java, Kotlin, Ruby, PHP, C, C++ and C# apps only so far");ensure!(d.is_finite() && d > 0.0, "--duration takes a number of seconds, e.g. --duration 30");}let exe = lang.resolve(&command[0], &ctx.root)?;