Repository navigation
feat(divan): run each benchmark in its own process #194
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
not-matthias
merged 8 commits into
main
from
cod-3799-explore-process-per-benchmark-in-codspeed-rust
Oct 21, 2026
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
b250112
chore(codspeed): drop unused libc dependency
not-matthias 06d80d9
feat(codspeed): add per-benchmark process isolation
not-matthias 43916f8
feat(divan): run each benchmark in its own process
not-matthias 5622bb3
feat(criterion): run each benchmark in its own process
not-matthias 9ee5ae0
test(cargo-codspeed): cover process isolation end to end
not-matthias 3218867
test(divan): add allocator ripple benchmark
not-matthias fef0566
ci: time out the analysis integration tests
not-matthias fce04a6
fix(criterion): send benchmark markers around iter_manual rounds
not-matthias File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
19 changes: 19 additions & 0 deletions
19
crates/cargo-codspeed/tests/process-isolation.in/Cargo.toml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| [package] | ||
| name = "process-isolation" | ||
| version = "0.0.0" | ||
| edition = "2021" | ||
| publish = false | ||
|
|
||
| [dependencies] | ||
| divan = { package = "codspeed-divan-compat", path = "../../../divan_compat" } | ||
| tokio = { version = "1.39", features = ["rt-multi-thread"] } | ||
|
|
||
| [workspace] | ||
|
|
||
| [[bench]] | ||
| name = "isolated" | ||
| harness = false | ||
|
|
||
| [[bench]] | ||
| name = "panicking" | ||
| harness = false | ||
28 changes: 28 additions & 0 deletions
28
crates/cargo-codspeed/tests/process-isolation.in/benches/isolated.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| use divan::Bencher; | ||
| use std::sync::LazyLock; | ||
| use tokio::runtime::Runtime; | ||
|
|
||
| /// Started in `main`, before any benchmark, so its worker threads belong to | ||
| /// the process that runs the harness. | ||
| static RUNTIME: LazyLock<Runtime> = | ||
| LazyLock::new(|| Runtime::new().expect("failed to start the Tokio runtime")); | ||
|
|
||
| #[divan::bench] | ||
| fn first(bencher: Bencher) { | ||
| bencher.bench(|| divan::black_box(1)); | ||
| } | ||
|
|
||
| #[divan::bench] | ||
| fn second(bencher: Bencher) { | ||
| bencher.bench(|| divan::black_box(2)); | ||
| } | ||
|
|
||
| #[divan::bench] | ||
| fn spawn_on_main_runtime(bencher: Bencher) { | ||
| bencher.bench(|| RUNTIME.block_on(async { tokio::spawn(async { 3 }).await.unwrap() })); | ||
| } | ||
|
|
||
| fn main() { | ||
| LazyLock::force(&RUNTIME); | ||
| divan::main(); | ||
| } |
8 changes: 8 additions & 0 deletions
8
crates/cargo-codspeed/tests/process-isolation.in/benches/panicking.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| #[divan::bench] | ||
| fn panics() { | ||
| panic!("benchmark failed"); | ||
| } | ||
|
|
||
| fn main() { | ||
| divan::main(); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| use predicates::str::contains; | ||
| use rstest::rstest; | ||
| use std::time::Duration; | ||
|
|
||
| mod helpers; | ||
| use helpers::*; | ||
|
|
||
| const DIR: &str = "tests/process-isolation.in"; | ||
| /// Process isolation only applies to analysis builds. | ||
| const MODE: [&str; 2] = ["-m", "simulation"]; | ||
| const PROCESS_ISOLATION_ENV: &str = "CODSPEED_PROCESS_ISOLATION"; | ||
| /// Exit code of a Rust process whose main thread panicked. | ||
| const PANIC_EXIT_CODE: i32 = 101; | ||
| /// Fails a run whose benchmark process got stuck instead of blocking the suite. | ||
| const RUN_TIMEOUT: Duration = Duration::from_secs(120); | ||
|
|
||
| fn build_and_run(dir: &String, bench: &str, isolation: &str) -> assert_cmd::assert::Assert { | ||
| cargo_codspeed(dir) | ||
| .args(["build", "--bench", bench]) | ||
| .args(MODE) | ||
| .assert() | ||
| .success(); | ||
| cargo_codspeed(dir) | ||
| .args(["run", "--bench", bench]) | ||
| .args(MODE) | ||
| .env(PROCESS_ISOLATION_ENV, isolation) | ||
| .timeout(RUN_TIMEOUT) | ||
| .assert() | ||
| } | ||
|
|
||
| #[rstest] | ||
| fn test_isolation_runs_all_benchmarks(#[values("true", "false")] isolation: &str) { | ||
| let dir = setup(DIR, Project::Simple); | ||
| build_and_run(&dir, "isolated", isolation) | ||
| .success() | ||
| .stdout(contains("isolated.rs::first")) | ||
| .stdout(contains("isolated.rs::second")) | ||
| .stdout(contains("isolated.rs::spawn_on_main_runtime")); | ||
| teardown(dir); | ||
| } | ||
|
|
||
| #[rstest] | ||
| fn test_isolation_fails_the_run_when_a_benchmark_panics( | ||
| #[values("true", "false")] isolation: &str, | ||
| ) { | ||
| let dir = setup(DIR, Project::Simple); | ||
| build_and_run(&dir, "panicking", isolation) | ||
| .code(PANIC_EXIT_CODE) | ||
| .stderr(contains("benchmark failed")); | ||
| teardown(dir); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,101 @@ | ||
| //! Process isolation: every benchmark runs in a fresh copy of the benchmark | ||
| //! executable, so the allocator state and threads that other benchmarks or | ||
| //! setup code leave behind can't change its measurement. | ||
|
|
||
| use std::{ | ||
| io::Write, | ||
| process::{Command, ExitStatus}, | ||
| sync::LazyLock, | ||
| }; | ||
|
|
||
| static CURRENT: LazyLock<Isolation> = LazyLock::new(Isolation::from_env); | ||
|
|
||
| /// Isolation is on unless this is `0` or `false`. | ||
| pub const PROCESS_ISOLATION_ENV: &str = "CODSPEED_PROCESS_ISOLATION"; | ||
| /// Set on each child process: the URI of the only benchmark it runs. | ||
| const ISOLATED_BENCHMARK_ENV: &str = "CODSPEED_ISOLATED_BENCHMARK"; | ||
|
|
||
| /// Exit code for a child that ended with neither an exit code nor a signal. | ||
| const GENERIC_FAILURE_EXIT_CODE: i32 = 1; | ||
| /// Shells report a child killed by signal N as exit code 128 + N. | ||
| #[cfg(unix)] | ||
| const SIGNAL_EXIT_CODE_OFFSET: i32 = 128; | ||
|
|
||
| /// How a harness runs each benchmark. | ||
| #[derive(Clone, Debug, PartialEq, Eq)] | ||
| pub enum Isolation { | ||
| /// All benchmarks share this process and its allocator state. | ||
| SharedProcess, | ||
| /// Every benchmark runs in its own child process. | ||
| ProcessPerBenchmark, | ||
| /// A child spawned by [`Isolation::ProcessPerBenchmark`], restricted to this URI. | ||
| IsolatedBenchmark(String), | ||
| } | ||
|
|
||
| impl Isolation { | ||
| /// The isolation of this process, read once from the environment. | ||
| pub fn current() -> &'static Self { | ||
| &CURRENT | ||
| } | ||
|
|
||
| fn from_env() -> Self { | ||
| if let Ok(uri) = std::env::var(ISOLATED_BENCHMARK_ENV) { | ||
| return Self::IsolatedBenchmark(uri); | ||
| } | ||
|
|
||
| match std::env::var(PROCESS_ISOLATION_ENV).as_deref() { | ||
| Err(_) | Ok("1" | "true") => Self::ProcessPerBenchmark, | ||
| Ok("0" | "false") => Self::SharedProcess, | ||
| Ok(other) => { | ||
| panic!("{PROCESS_ISOLATION_ENV} must be `true` or `false`, got `{other}`") | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// The only benchmark this process may run. It overrides CLI filters. | ||
| pub fn only_benchmark(&self) -> Option<&str> { | ||
| match self { | ||
| Self::IsolatedBenchmark(uri) => Some(uri), | ||
| Self::SharedProcess | Self::ProcessPerBenchmark => None, | ||
| } | ||
| } | ||
|
|
||
| /// Runs the benchmark `uri`. `bench` must contain the whole measurement, | ||
| /// from `start_benchmark` to `end_benchmark`. | ||
| pub fn run(&self, uri: String, bench: impl FnOnce(String)) { | ||
| match self { | ||
| Self::SharedProcess | Self::IsolatedBenchmark(_) => bench(uri), | ||
| Self::ProcessPerBenchmark => run_in_child_process(&uri), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// Runs this executable again with the same arguments, limited to `uri`, and | ||
| /// exits with the child's code if it fails. | ||
| fn run_in_child_process(uri: &str) { | ||
| // Keep the parent's output before the child's. | ||
| if let Err(error) = std::io::stdout().flush() { | ||
| eprintln!("failed to flush stdout before running {uri}: {error}"); | ||
| } | ||
|
|
||
| let exe = std::env::current_exe().expect("failed to locate the benchmark executable"); | ||
| let status = Command::new(exe) | ||
| .args(std::env::args_os().skip(1)) | ||
| .env(ISOLATED_BENCHMARK_ENV, uri) | ||
| .status() | ||
| .unwrap_or_else(|error| panic!("failed to start the process for {uri}: {error}")); | ||
|
|
||
| if !status.success() { | ||
| std::process::exit(exit_code(status)); | ||
| } | ||
| } | ||
|
|
||
| /// Exit code of a failed child, in the shell convention. | ||
| fn exit_code(status: ExitStatus) -> i32 { | ||
| #[cfg(unix)] | ||
| if let Some(signal) = std::os::unix::process::ExitStatusExt::signal(&status) { | ||
| return SIGNAL_EXIT_CODE_OFFSET + signal; | ||
| } | ||
|
|
||
| status.code().unwrap_or(GENERIC_FAILURE_EXIT_CODE) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,7 @@ | ||
| pub mod codspeed; | ||
|
|
||
| pub mod instrument_hooks; | ||
| pub mod isolation; | ||
|
|
||
| mod macros; | ||
| mod measurement; | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.