CARGO-BENCH(1)
π cargo-bench β the manual, bestie edition (part 1 of 2) π
okay so. <pink>CARGO-BENCH</pink>, from the General Commands Manual section, aka the page you open when you're like "how do I run my benches again". Sit down, grab a boba, we're doing this. π§β¨
πΈ NAME πΈ
cargo-bench β bestie, it executes benchmarks of a package. That's the whole vibe. π
β¨ SYNOPSIS β¨
cargo bench [options] [benchname] [-- bench-options]
look at her. so simple. so powerful. π
π¦ DESCRIPTION π¦
It compiles your benchmarks and then runs them. Iconic behaviour honestly. π
So here's the tea on how arguments work, because this is where people get confused and I refuse to let that be you:
The benchmark filtering argument benchname and all the arguments that come after the two dashes (--) get passed to the benchmark binaries, and from there they land in libtest (that's rustc's built-in unit-test and micro-benchmarking framework, for the uninitiated β¨). So if you're throwing arguments at both Cargo and the binary, here's the rule: everything after -- goes to the binary, everything before it goes to Cargo. Two lanes, no overlap. π£οΈ
Wanna know the deets on libtest's arguments? Run cargo bench -- --help and read what it spits out, and also go check the rustc book's chapter on how tests work over at <https://doc.rust-lang.org/rustc/tests/index.html>. iykyk π
Example time, because examples eat every time:
cargo bench -- foo --exact
This one runs only the benchmark named foo, and skips other similarly named benchmarks like foobar. --exact said "no crumbs, only the real one". π
Now, how do benches even get built? 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 the 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 that harness is libtest or a custom harness. no cap. π₯
You can also turn the libtest harness off entirely by setting harness = false in the target manifest settings. In that case, bestie, your code has to provide its own main function to handle running benchmarks. You're on your own β main character energy, but make it fn main(). π«‘
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>). If you're on stable and sad about it π, there are some packages 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>). She's giving "there's a crate for that" and honestly? true.
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. That's the whole point β you want the optimized numbers, not the debug-build lies. ποΈ
But what if you need to debug a benchmark? Valid. Use the --profile=dev command-line option to switch to the dev profile instead. Then you can run the debug-enabled benchmark inside a debugger. Detective mode activated π΅οΈβοΈ
π 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 the working directory of benchmarks 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 actually executed from. So no matter where you're standing when you yell at Cargo, the bench still knows where home is. π‘π
π OPTIONS π
π₯ Benchmark Options
--no-runβ Compile, but don't run the benchmarks. Build only. It's giving "look, don't touch". π--no-fail-fastβ Run all benchmarks regardless of failure. Without this flag, Cargo will exit after the first executable fails. Important deets: the Rust test harness will run all benchmarks within the executable to completion on its own β this flag only applies to the executable as a whole. So it's about not bailing early at the executable level, okay? β οΈ
π 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 will be selected. That's just how she moves. β¨
The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set:
- a virtual workspace will include all workspace members (equivalent to passing
--workspace) - a non-virtual workspace will include only the root crate itself
-pspecβ¦,--packagespecβ¦ β 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 β and listen closely β to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. your shell is nosy, protect your globs π‘οΈ--workspaceβ Benchmark all members in the workspace. everyone's invited to the party π--allβ Deprecated alias for--workspace. it's giving vintage. still works, still deprecated, don't @ me π--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. (same warning, same energy, wrap your globs bestie π)
π 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. yes, it really does that. π
Setting targets to bench = false will stop them from being benchmarked by default. But β plot twist β target selection options that take a target by name (such as --example foo) ignore the bench flag and will always benchmark the given target. Named targets don't take no for an answer. π
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, so that it can use the env macro (<https://doc.rust-lang.org/std/macro.env.html>) to locate the executable. so helpful of Cargo, honestly π₯Ή
Passing target selection flags will benchmark only the specified targets.
Note that--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. same rule, every time, forever π
--libβ Benchmark the package's library. the classic. π--bin*name*β¦ β Benchmark the specified binary. This flag may be specified multiple times and supports common Unix glob patterns.--binsβ Benchmark all binary targets. all of them. every single one. ποΈ--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 in test mode 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 thelibtarget 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. double the build, double the fun π--bench*name*β¦ β Benchmark the specified benchmark. This flag may be specified multiple times and supports common Unix glob patterns.--benchesβ Benchmark all targets in benchmark mode 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 thelibtarget 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. yes, twice again. she's thorough π--all-targetsβ Benchmark all targets. This is equivalent to specifying--lib --bins --tests --benches --examples. the "do everything" button, basically π
π¦ 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. stack them like bracelets π«Ά--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. sometimes you just want the bare minimum, and that's valid π
π§ Compilation Options
--targettriple β Benchmark for the given architecture. The default is the host architecture. The general format of the triple is<arch><sub>-<vendor>-<sys>-<abi>. Runrustc --print target-listfor a list of supported targets. This flag may be specified multiple times.
This may also be specified with the build.target config value (<https://doc.rust-lang.org/cargo/reference/config.html>).
Note that 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/guide/build-cache.html>) documentation for more details. new folder, new vibe, new disk usage π
--profilename β Benchmark with the given profile. See the reference (<https://doc.rust-lang.org/cargo/reference/profiles.html>) for more details on profiles. pick your fighter π₯--timings=fmtsβ Output information how long each compilation takes, and track concurrency information over time. Accepts an optional comma-separated list of output formats;--timingswithout an argument will default to--timings=html. Specifying an output format (rather than the default) is unstable and requires-Zunstable-options. Valid output formats:html(unstable, needs-Zunstable-options) β writes a whole human-readable file calledcargo-timing.htmlinto thetarget/cargo-timingsdirectory, and it's literally a report of the compilation π . It'll also drop a report in that same directory with a timestamp in the filename, so if you wanna peek at older runs you totally can. Lowkey important: HTML output is for human eyeballs only, it does not give you machine-readable timing data. Bestie, do not try to parse it. πjson(unstable, needs-Zunstable-options) β spits out machine-readable JSON info about the timing stuff. For when you want your tools to do the reading instead of you. β¨
π Output Options π
--target-dirdirectory β the directory where all the generated artifacts and intermediate files go. You can also set this with theCARGO_TARGET_DIRenvironment variable, or via thebuild.target-dirconfig value (https://doc.rust-lang.org/cargo/reference/config.html). If you don't say anything, it defaults totargetin the root of the workspace. π
πΈ Display Options πΈ
Okay so by default the Rust test harness hides output from benchmark execution, just so the results stay readable (iconic behaviour honestly). But if you want that output back β say, for debugging β you can recover it by passing --nocapture to the benchmark binaries:
cargo bench -- --nocapture
-v,--verboseβ verbose output, queen. You can pass it twice for "very verbose" output, which throws in extra stuff like dependency warnings and build script output. Can also be set with theterm.verboseconfig value (https://doc.rust-lang.org/cargo/reference/config.html). π-q,--quietβ do not print cargo log messages. Silence is golden, no cap. Can also be set with theterm.quietconfig value (https://doc.rust-lang.org/cargo/reference/config.html). π€«--colorwhen β controls when colored output gets used. Valid values:auto(default): automatically detects if the terminal supports color. Very "I'll read the room" of it.always: always display colors. π periodt.never: never display colors.
May also be specified 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 bunch of comma-separated values. Valid values:human(default): display in a human-readable text format. Conflicts withshortandjson. πshort: emit shorter, human-readable text messages. Conflicts withhumanandjson.json: emit JSON messages to stdout. See the reference (https://doc.rust-lang.org/cargo/reference/external-tools.html#json-messages) for more deets. Conflicts withhumanandshort.json-diagnostic-short: makes sure therenderedfield of JSON messages contains the "short" rendering 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 others coming from rustc, are still emitted. Cannot be used withhumanorshort.
π Manifest Options π
--manifest-pathpath β path to theCargo.tomlfile. By default, Cargo goes hunting forCargo.tomlin the current directory or any parent directory. π--ignore-rust-versionβ ignore therust-versionspecification in packages. Living on the edge, I respect it. π¦--lockedβ asserts that the exact same dependencies and versions get used as when the existingCargo.lockfile was originally generated. Cargo will exit with an error when either of these scenarios comes up:- The lock file is missing. π
- Cargo attempted to change the lock file because of a different dependency resolution.
It may be used in environments where deterministic builds are the goal, like in CI pipelines. Very much giving "reproducible or nothing". β¨
--offlineβ prevents Cargo from touching the network for any reason. Without this flag, Cargo stops with an error if it needs the network and the network isn't there. With this flag, Cargo will try to carry on without the network if it possibly can. πβ
Beware bestie: this can result in different dependency resolution than online mode. Cargo restricts itself to crates that are downloaded locally, even if there might be a newer version indicated in the local copy of the index. See cargo-fetch(1) to download dependencies before you go offline. π
May also be specified with the net.offline config value (https://doc.rust-lang.org/cargo/reference/config.html).
--frozenβ equivalent to specifying both--lockedand--offlineat the same time. Two-for-one special. π--lockfile-pathPATH β changes the path of the lockfile from the default (<workspace_root>/Cargo.lock) to PATH. PATH must end withCargo.lock(e.g.--lockfile-path /tmp/temporary-lockfile/Cargo.lock). Heads up: providing--lockfile-pathwill ignore the existing lockfile at the default path, and will instead either use the lockfile from PATH, or write a brand-new lockfile into the provided PATH if it doesn't exist. This flag can be used to run most commands in read-only directories, writing the lockfile into the provided PATH. π
This option is only available on the nightly channel (https://doc.rust-lang.org/book/appendix-07-nightly-rust.html) and requires the-Z unstable-optionsflag to enable (see #14421https://github.com/rust-lang/cargo/issues/14421). Nightly-only, iykyk. π
π Common Options π
+toolchain β if Cargo was installed with rustup, and the first argument tocargostarts with+, it gets interpreted as a rustup toolchain name (like+stableor+nightly). See the rustup documentation (https://rust-lang.github.io/rustup/overrides.html) for more info on how toolchain overrides work. π§--configKEY=VALUE or PATH β overrides a Cargo configuration value. The argument should either be in TOML syntax ofKEY=VALUE, or given as a path to an extra configuration file. This flag may be specified 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 searched when discovering.cargo/config.toml, for example. 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 requires the-Z unstable-optionsflag to enable (see #10098https://github.com/rust-lang/cargo/issues/10098). π
-h,--helpβ prints help information. The classic. The main character of every terminal session. π-Zflag β unstable (nightly-only) flags for Cargo. Runcargo -Z helpfor the details. β‘
π¦ Miscellaneous Options π¦
Real talk: the --jobs argument affects the building of the benchmark executable, but it does not affect how many threads are used when running the benchmarks. The Rust test harness runs benchmarks serially, in a single thread. One at a time. No multitasking here bestie. π
-jN,--jobsN β number of parallel jobs to run. May also be specified 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 provided value. If a stringdefaultis provided, it sets the value back to defaults. And it should not be0. π«
While cargo bench does involve compilation, it does not provide a --keep-going flag. Use --no-fail-fast to run as many benchmarks as possible without stopping at the first failure. And if you want to "compile" as many benchmarks as possible, use --benches to build the benchmark binaries separately. Like this:
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 the deets on environment variables that Cargo reads. π±
β EXIT STATUS β
0: Cargo succeeded. π slay.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 a wrap bestie π«Ά this whole page lives under CARGO-BENCH(1) β that's the name right there at the bottom, the source-and-version-and-date flex at the end of the manpage. Go run some benchmarks, you absolute icon. π
β¨π
π¦ where this page comes from
- ubuntu jammy: cargo-1.82 1.82.0+dfsg0ubuntu0~jammy-0ubuntu0.22.04.1 Β· Apache-2.0 WITH LLVM exception
- ubuntu noble: cargo-1.82 1.82.0+dfsg0ubuntu0-0ubuntu0.24.04.1 Β· Apache-2.0 WITH LLVM exception
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms