CARGO-BENCH(1)
π NAME π
cargo-bench β Execute benchmarks of a package
β¨ SYNOPSIS β¨
cargo bench [options] [benchname] [-- bench-options]
πΈ DESCRIPTION πΈ
okay so bestie, cargo bench compiles and runs your benchmarks. That's the whole vibe. π
The benchmark filtering argument benchname and all the arguments following the two dashes (--) get passed straight to the benchmark binaries and thus to libtest (rustc's built in unit-test and micro-benchmarking framework). If you're passing arguments to both Cargo and the binary, the ones after -- go to the binary, and the ones before go to Cargo. For all the details about libtest's arguments, peep the output of 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. π¦
As an example, this will run only the benchmark named foo (and skip 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. The executable automatically runs all functions annotated with the #[bench] attribute. 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. No cap. π
The libtest harness may be disabled by setting harness = false in the target manifest settings, in which case your code will need to provide its own main function to handle running benchmarks.
Note: The#[bench]attribute athttps://doc.rust-lang.org/nightly/unstable-book/library-features/test.htmlis currently unstable and only available on the nightly channel athttps://doc.rust-lang.org/book/appendix-07-nightly-rust.html. There are some packages available on crates.io athttps://crates.io/keywords/benchmarkthat may help with running benchmarks on the stable channel, such as Criterion athttps://crates.io/crates/criterion.
By default, cargo bench uses the bench profile at 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. You can then run the debug-enabled benchmark within a debugger. It's giving "I know what I'm doing" energy. π₯
π Working directory of benchmarks π
The working directory of every benchmark is set to the root directory of the package the benchmark belongs to. 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 from where cargo bench was executed from. So iconic. π
π OPTIONS π
π Benchmark Options π
--no-runβ Compile, but don't run benchmarks. literally just build them and dip.--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. Bestie, it's the "we don't stop, we keep going" button. πͺ
π¦ 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 workspaces default members are selected, otherwise only the package defined by the manifest will be selected.
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), and a non-virtual workspace will include only the root crate itself. The way that Cargo does defaults is lowkey so extra. π
-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, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. quote it, bestie, or the shell will do too much. π--workspaceβ Benchmark all members in the workspace. all of them. periodt. π--allβ Deprecated alias for--workspace. it's giving legacy, but it's still here.--excludeSPECβ¦β 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. not me excluding a package from the workspace party. π
π― 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 at 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 at 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 at https://doc.rust-lang.org/std/macro.env.html to locate the executable. iykyk. π«Ά
Passing target selection flags will benchmark only the specified targets.
Note that --bin, --example, --test and --bench flags 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 energy as before: quote your globs. β¨
--libβ Benchmark the package's library. the lib is the main character here. π--binnameβ¦β Benchmark the specified binary. This flag may be specified multiple times and supports common Unix glob patterns.--binsβ Benchmark all binary targets. every single bin, no skips. π--examplenameβ¦β Benchmark the specified example. This flag may be specified multiple times and supports common Unix glob patterns.--examplesβ Benchmark all example targets. examples are eating, fr fr. π--testnameβ¦β 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.--benchnameβ¦β 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. literally the "give me everything" combo. π
β¨ Feature Selection β¨
The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package.
See the features documentation at 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. feature combo slay. π--all-featuresβ Activate all available features of all selected packages. all of them. no cap. π₯--no-default-featuresβ Do not activate the default feature of the selected packages. sometimes you gotta say no to the default. π
π οΈ 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 at 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 at https://doc.rust-lang.org/cargo/reference/build-cache.html documentation for more details. different directory, different vibe. π¦
--profilenameβ Benchmark with the given profile. See the reference athttps://doc.rust-lang.org/cargo/reference/profiles.htmlfor more details on profiles. choose 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, with 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. Bestie, listen: HTML output is for humans only, it does not give you machine-readable timing data. No cap.json(unstable, needs-Zunstable-options) β emits machine-readable JSON info about timing information. That's the one your scripts want. π₯
β¨ Output Options β¨
--target-dirdirectory β the directory for all the generated artifacts and intermediate files, i.e. where all the stuff goes. 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>. Defaults totargetin the root of the workspace. π
πΈ Display Options πΈ
Okay so by default the Rust test harness hides output from benchmark execution, purely to keep the results readable (it's giving considerate). But if you want that output back β say, for debugging β you can recover it by passing --nocapture to the benchmark binaries, like this:
cargo bench -- --nocapture
Obsessed, honestly. π
-v,--verboseβ use verbose output. You can specify it twice for "very verbose" output, which includes extra stuff like dependency warnings and build script output. May also be specified with theterm.verboseconfig value <https://doc.rust-lang.org/cargo/reference/config.html>.-q,--quietβ do not print cargo log messages. May also be specified with theterm.quietconfig value <https://doc.rust-lang.org/cargo/reference/config.html>. Shhh. π€«--colorwhen β controls when colored output is used. Valid values:auto(default): automatically detects if color support is available on the terminal.always: always display colors.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. Can be specified multiple times, and it's made 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 details. Conflicts withhumanandshort.json-diagnostic-short: ensure therenderedfield of JSON messages contains the "short" rendering from rustc. Cannot be used withhumanorshort.json-diagnostic-rendered-ansi: ensure therenderedfield of JSON messages contains embedded ANSI color codes, so it respects rustc's default color scheme. Cannot be used withhumanorshort.json-render-diagnostics: tells Cargo not to include rustc diagnostics in the JSON messages it prints, and instead Cargo itself should render the JSON diagnostics coming from rustc. Cargo's own JSON diagnostics, plus the others coming from rustc, are still emitted. Cannot be used withhumanorshort.
π¦ Manifest Options π¦
--manifest-pathpath β path to theCargo.tomlfile. By default, Cargo searches for theCargo.tomlfile in the current directory or any parent directory. She's thorough like that. π--ignore-rust-versionβ ignore therust-versionspecification in packages.--lockedβ asserts that the exact same dependencies and versions are used as when the existingCargo.lockfile was originally generated. Cargo will exit with an error when either of these scenarios arises:- The lock file is missing.
- Cargo attempted to change the lock file due to a different dependency resolution.
It may be used in environments where deterministic builds are desired, such as in CI pipelines. Determinism is so main character. π
--offlineβ prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network isn't available. With this flag, Cargo will attempt to proceed without the network if possible.
Beware bestie: this may result in a different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See cargo-fetch(1) to download dependencies before going 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--offline. Two vibes, one flag. β¨--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). Note that providing--lockfile-pathwill ignore the existing lockfile at the default path, and instead will either use the lockfile from PATH, or write a 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-options flag to enable (see #14421 <https://github.com/rust-lang/cargo/issues/14421>). π
π Common Options π
+toolchain β if Cargo has been installed with rustup, and the first argument tocargobegins with+, it'll be interpreted as a rustup toolchain name (such as+stableor+nightly). See the rustup documentation <https://rust-lang.github.io/rustup/overrides.html> for more info about how toolchain overrides work. So fancy. π--configKEY=VALUE or PATH β overrides a Cargo configuration value. The argument should be in TOML syntax ofKEY=VALUE, or provided 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 information.-CPATH β changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest (Cargo.toml), as well as the directories searched for discovering.cargo/config.toml, for example. This option must appear before the command name, for examplecargo -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-options flag to enable (see #10098 <https://github.com/rust-lang/cargo/issues/10098>). π
-h,--helpβ prints help information. The classic. π«Ά-Zflag β unstable (nightly-only) flags to Cargo. Runcargo -Z helpfor details.
π Miscellaneous Options π
Heads up, this one's important: 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, bestie. Periodt.
-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 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. Should not be0. π«
So, while cargo bench involves 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 to "compile" as many benchmarks as possible, use --benches to build benchmark binaries separately. For example:
cargo build --benches --release --keep-going
cargo bench --no-fail-fast
Chef's kiss. π₯
π ENVIRONMENT π
See the reference <https://doc.rust-lang.org/cargo/reference/environment-variables.html> for details on environment variables that Cargo reads.
β 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 β this was the CARGO-BENCH(1) manual, the one you find filed under Cargo's own docs, version and date included, sitting right at the bottom of the page like a little signature. Go bench something iconic. πβ¨π
π¦ where this page comes from
- ubuntu jammy: cargo-1.89 1.89.0+dfsg~24.04-0ubuntu0.22.04.2 Β· Apache-2.0 WITH LLVM exception
- ubuntu noble: cargo-1.89 1.89.0+dfsg~24.04-0ubuntu0.24.04.2 Β· 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