CARGO-BENCH(1)
π CARGO-BENCH π
okay bestie, welcome to the cargo-bench page β it's part of the General Commands Manual, and it's literally your girl for running benchmarks. let's get into it π
β¨ NAME β¨
cargo-bench β Execute benchmarks of a package π
πΈ SYNOPSIS πΈ
cargo bench [options] [benchname] [-- bench-options]
π¦ DESCRIPTION π¦
Compile and execute benchmarks. periodt.
So here's the vibe: the benchmark filtering argument benchname, plus everything after the two dashes (--), gets passed straight to the benchmark binaries β which means it goes to libtest (that's rustc's built-in unit-test and micro-benchmarking framework, iykyk). If you're passing args to both Cargo and the binary, the ones after -- go to the binary and the ones before go to Cargo. no cap.
Wanna know the deets on libtest's arguments? Run cargo bench -- --help and check out the rustc book's chapter on how tests work at <https://doc.rust-lang.org/rustc/tests/index.html>.
Here's an example β this runs only the benchmark named foo, and skips other similarly named benchmarks like foobar:
cargo bench -- foo --exact
Benchmarks are built with the --test option to rustc, which creates a special executable by linking your code with libtest. That executable automatically runs all functions annotated with the #[bench] attribute. And Cargo passes the --bench flag to the test harness to tell it to run only benchmarks, regardless of whether the harness is libtest or a custom harness. slay.
You can disable the libtest harness by setting harness = false in the target manifest settings β but then your code has to provide its own main function to handle running benchmarks. you're on your own for that one π
Note: The #[bench] attribute <https://doc.rust-lang.org/nightly/unstable-book/library-features/test.html> is currently unstable and only available on the nightly channel <https://doc.rust-lang.org/book/appendix-07-nightly-rust.html>. There are some packages available on crates.io <https://crates.io/keywords/benchmark> that may help with running benchmarks on the stable channel, such as Criterion <https://crates.io/crates/criterion>. π«Ά
By default, cargo bench uses the bench profile <https://doc.rust-lang.org/cargo/reference/profiles.html#bench>, which enables optimizations and disables debugging information. If you need to debug a benchmark, you can use the --profile=dev command-line option to switch to the dev profile. Then you can run the debug-enabled benchmark inside a debugger. π debugging benchmarks is a whole journey, good luck bestie.
π§ Working directory of benchmarks π§
The working directory of every benchmark is set to the root directory of the package the benchmark belongs to. Why? Because setting it to the package's root directory makes it possible for benchmarks to reliably access the package's files using relative paths β regardless of where cargo bench was executed from. iconic behaviour honestly.
π OPTIONS π
π₯ Benchmark Options π₯
--no-runβ Compile, but don't run benchmarks. just build it and stare at it.--no-fail-fastβ Run all benchmarks regardless of failure. Without this flag, Cargo will exit after the first executable fails. The Rust test harness will run all benchmarks within the executable to completion β this flag only applies to the executable as a whole. so it's like, per-executable energy, not per-benchmark.
π Package Selection π
By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace, then the workspace's default members are selected; otherwise only the package defined by the manifest gets selected.
The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If that's not set, a virtual workspace will include all workspace members (equivalent to passing --workspace), and a non-virtual workspace will include only the root crate itself.
-p*spec*β¦,--package*spec*β¦ β Benchmark only the specified packages. Seecargo-pkgid(1)for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like*,?and[]. However β to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. yes really, quote them, don't let your shell ruin the moment π--workspaceβ Benchmark all members in the workspace. the whole squad.--allβ Deprecated alias for--workspace. it's giving legacy, use the new one bestie.--exclude*SPEC*β¦ β Exclude the specified packages. Must be used in conjunction with the--workspaceflag. This flag may be specified multiple times and supports common Unix glob patterns like*,?and[]. However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern.
π Target Selection π
When no target selection options are given, cargo bench will build the following targets of the selected packages:
libβ used to link with binaries and benchmarksbins(only if benchmark targets are built and required features are available)libas a benchmarkbinsas benchmarks- benchmark targets
The default behavior can be changed by setting the bench flag for the target in the manifest settings. Setting examples to bench = true will build and run the example as a benchmark, replacing the example's main function with the libtest harness.
Setting targets to bench = false will stop them from being benchmarked by default. Target selection options that take a target by name (such as --example foo) ignore the bench flag and will always benchmark the given target.
See Configuring a target <https://doc.rust-lang.org/cargo/reference/cargo-targets.html#configuring-a-target> for more information on per-target settings.
Binary targets are automatically built if there is an integration test or benchmark being selected to benchmark. This allows an integration test to execute the binary to exercise and test its behavior. The CARGO_BIN_EXE_<name> environment variable <https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates> is set when the integration test is built and run, so that it can use the env macro <https://doc.rust-lang.org/std/macro.env.html> or the var function <https://doc.rust-lang.org/std/env/fn.var.html> to locate the executable. so handy fr fr.
Passing target selection flags will benchmark only the specified targets.
Note:--bin,--example,--testand--benchflags also support common Unix glob patterns like*,?and[]. However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each glob pattern. π«Ά
--libβ Benchmark the package's library.--bin*name*β¦ β Benchmark the specified binary. This flag may be specified multiple times and supports common Unix glob patterns.--binsβ Benchmark all binary targets.--example*name*β¦ β Benchmark the specified example. This flag may be specified multiple times and supports common Unix glob patterns.--examplesβ Benchmark all example targets.--test*name*β¦ β Benchmark the specified integration test. This flag may be specified multiple times and supports common Unix glob patterns.--testsβ Benchmark all targets that have thetest = truemanifest flag set. By default this includes the library and binaries built as unittests, and integration tests. Be aware that this will also build any required dependencies, so the lib target may be built twice (once as a unittest, and once as a dependency for binaries, integration tests, etc.). Targets may be enabled or disabled by setting thetestflag in the manifest settings for the target.--bench*name*β¦ β Benchmark the specified benchmark. This flag may be specified multiple times and supports common Unix glob patterns.--benchesβ Benchmark all targets that have thebench = truemanifest flag set. By default this includes the library and binaries built as benchmarks, and bench targets. Be aware that this will also build any required dependencies, so the lib target may be built twice (once as a benchmark, and once as a dependency for binaries, benchmarks, etc.). Targets may be enabled or disabled by setting thebenchflag in the manifest settings for the target.--all-targetsβ Benchmark all targets. This is equivalent to specifying--lib --bins --tests --benches --examples. the full package deal π
π Feature Selection π
The feature flags let you control which features are enabled. When no feature options are given, the default feature is activated for every selected package.
See the features documentation <https://doc.rust-lang.org/cargo/reference/features.html#command-line-feature-options> for more details.
-Ffeatures,--featuresfeatures β Space or comma separated list of features to activate. Features of workspace members may be enabled withpackage-name/feature-namesyntax. This flag may be specified multiple times, which enables all specified features. yes, stack them.--all-featuresβ Activate all available features of all selected packages. go big or go home.--no-default-featuresβ Do not activate the default feature of the selected packages. βοΈ bye default.
β Compilation Options β
--targettriple β Benchmark for the specified target architecture. Flag may be specified multiple times. The default is the host architecture. The general format of the triple is<arch><sub>-<vendor>-<sys>-<abi>.
Possible values:
- Any supported target in
rustc --print target-list. "host-tuple", which will internally be substituted by the host's target. This can be particularly useful if you're cross-compiling some crates, and don't want to specify your host's machine as a target (for instance, an xtask in a shared project that may be worked on by many hosts).- A path to a custom target specification. See Custom Target Lookup Path <https://doc.rust-lang.org/rustc/targets/custom.html#custom-target-lookup-path> for more information.
This may also be specified with the build.target config value <https://doc.rust-lang.org/cargo/reference/config.html>.
Note: specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache <https://doc.rust-lang.org/cargo/reference/build-cache.html> documentation for more details. π different directory, different rules.
--profilename β Benchmark with the given profile. See the reference <https://doc.rust-lang.org/cargo/reference/profiles.html> for more details on profiles.--timingsβ Output information how long each compilation takes, and track concurrency information over time. β±οΈ timing girlie.
Okay so real talk about those timing reports π
β cargo-timing.html gets written into the target/cargo-timings directory once the build finishes. And because the universe loves you, an extra report also gets written with a timestamp baked into its filename, so if you wanna scroll back and stare at a previous run, go off. One thing though: these reports are for human consumption only, okay? They do not give you machine-readable timing data. Not a crumb. π
β¨ Output Options β¨
--target-dirdirectory β this is the home for literally every generated artifact and intermediate file. You can also set it with theCARGO_TARGET_DIRenvironment variable, or via thebuild.target-dirconfig value (https://doc.rust-lang.org/cargo/reference/config.html). If you say nothing at all, it defaults totargetin the root of the workspace. She's predictable like that π
π Display Options π
Okay so by default the Rust test harness is lowkey a hater and hides all output from benchmark execution, just to keep the results readable. But bestie, you can absolutely recover that benchmark output (say, for debugging) by passing --no-capture to the benchmark binaries:
cargo bench -- --no-capture
-v,--verboseβ verbose output, obviously. Say it twice and you unlock "very verbose" mode, which serves up extra goodies like dependency warnings and build script output. You can also set this with theterm.verboseconfig value (https://doc.rust-lang.org/cargo/reference/config.html).-q,--quietβ do not print cargo log messages. Silence. Shhh. π€« Can also be set with theterm.quietconfig value (https://doc.rust-lang.org/cargo/reference/config.html).--colorwhen β controls when colored output happens. The valid values are:auto(default): automatically detects whether your terminal supports color, and acts accordingly.always: colors. Always. No matter what. πnever: no colors ever, we're going monochrome.
Can also be set with the term.color config value (https://doc.rust-lang.org/cargo/reference/config.html).
--message-formatfmt β the output format for diagnostic messages. You can pass this multiple times, and each one is a comma-separated list of values. The valid values are:human(default): displays in a human-readable text format. Conflicts withshortandjson.short: emits shorter, human-readable text messages. Conflicts withhumanandjson.json: emits JSON messages to stdout. Peep the reference (https://doc.rust-lang.org/cargo/reference/external-tools.html#json-messages) for more details. Conflicts withhumanandshort.json-diagnostic-short: makes sure therenderedfield of JSON messages contains the "short" rendering straight from rustc. Cannot be used withhumanorshort.json-diagnostic-rendered-ansi: makes sure therenderedfield of JSON messages contains embedded ANSI color codes, so rustc's default color scheme is respected. Cannot be used withhumanorshort.json-render-diagnostics: tells Cargo to not include rustc diagnostics in the JSON messages it prints, and instead have Cargo itself render the JSON diagnostics coming from rustc. Cargo's own JSON diagnostics β and the other ones coming from rustc β are still emitted. Cannot be used withhumanorshort.
π Manifest Options π
--manifest-pathpath β the path to theCargo.tomlfile. If you don't give one, Cargo goes hunting forCargo.tomlin the current directory, and then in every parent directory above it. She's thorough π--ignore-rust-versionβ ignores therust-versionspecification in packages. YOLO.--lockedβ this one asserts that the exact same dependencies and versions are used as when the existingCargo.lockfile was originally generated. Cargo will exit with an error if either of these scenarios pops up:- The lock file is missing. π
- Cargo attempted to change the lock file because of a different dependency resolution.
Use it in environments where you want deterministic builds β CI pipelines, for example. Iconic behaviour, honestly.
--offlineβ prevents Cargo from touching the network for any reason. Without this flag, Cargo just stops with an error if it needs the network and the network isn't there. With the flag, Cargo will try to carry on without the network if it possibly can.
Beware bestie: this may result in a different dependency resolution than online mode. Cargo restricts itself to crates that are already downloaded locally, even if a newer version exists according to the local copy of the index. If you wanna go offline properly, see the cargo-fetch(1) command to download your dependencies first. π«Ά
Can also be set with the net.offline config value (https://doc.rust-lang.org/cargo/reference/config.html).
--frozenβ equivalent to specifying both--lockedand--offline. Two for one, slay.
π οΈ Common Options π οΈ
+toolchain β if Cargo was installed with rustup, and the first argument tocargostarts with+, it gets interpreted as a rustup toolchain name (things like+stableor+nightly). The rustup documentation (https://rust-lang.github.io/rustup/overrides.html) has more on how toolchain overrides work.--configKEY=VALUE or PATH β overrides a Cargo configuration value. The argument should be in TOML syntax asKEY=VALUE, or it can be a path to an extra configuration file. You can pass this flag multiple times. See the command-line overrides section (https://doc.rust-lang.org/cargo/reference/config.html#command-line-overrides) for more.-CPATH β changes the current working directory before executing any of the specified operations. This affects stuff like where cargo looks by default for the project manifest (Cargo.toml), and also the directories it searches when discovering.cargo/config.toml. Heads up: this option must appear before the command name, likecargo -C path/to/my-project build.
This option is only available on the nightly channel (https://doc.rust-lang.org/book/appendix-07-nightly-rust.html) and it requires the -Z unstable-options flag to enable. See #10098 (https://github.com/rust-lang/cargo/issues/10098) for the deets.
-h,--helpβ prints help information. Classic.-Zflag β unstable (nightly-only) flags for Cargo. Runcargo -Z helpfor the details. π₯
π§ Miscellaneous Options π§
Okay important vibe check: the --jobs argument affects the building of the benchmark executable, but it does not affect how many threads get used when the benchmarks actually run. The Rust test harness runs benchmarks serially, in a single thread. That's just the law. π
-jN,--jobsN β the number of parallel jobs to run. Can also be set with thebuild.jobsconfig value (https://doc.rust-lang.org/cargo/reference/config.html). Defaults to the number of logical CPUs. If it's negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus the value you provided. If you provide a stringdefault, it resets the value back to the defaults. And it should not be0. Do not do that. π
So like, cargo bench does involve compilation, but it does not give you a --keep-going flag. Instead, use --no-fail-fast to run as many benchmarks as possible without stopping at the very first failure. And if you wanna "compile" as many benchmarks as possible, use --benches to build the benchmark binaries separately. For example:
cargo build --benches --release --keep-going
cargo bench --no-fail-fast
π ENVIRONMENT π
See the reference (https://doc.rust-lang.org/cargo/reference/environment-variables.html) for all the details on the environment variables that Cargo reads. She's nosy, but in a cute way. π
π¦ EXIT STATUS π¦
0: Cargo succeeded. π101: Cargo failed to complete. π
π EXAMPLES π
- Build and execute all the benchmarks of the current package:
cargo bench
- Run only a specific benchmark within a specific benchmark target:
cargo bench --bench bench_name -- modname::some_benchmark
π SEE ALSO π
And that's the whole page, bestie π«Ά huge shoutout to the Cargo crew for the source, the version, and the date stamped on this thing β this was CARGO-BENCH(1), and yes, it ate. Go forth and benchmark. π β¨
π¦ where this page comes from
- ubuntu stonking: cargo-1.97 1.97.1+dfsg-0ubuntu1 Β· MIT OR Apache-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms