CARGO-BENCH(1)

πŸ“¦ version 1.84.1, in ubuntu jammy, ubuntu noble

πŸ’… NAME πŸ’…

cargo-bench β€” execute benchmarks of a package πŸ’– this is the manual page for it, from the General Commands Manual (section 1), and bestie we are going to get you fluent in it.


πŸŽ€ SYNOPSIS πŸŽ€

cargo bench [options] [benchname] [-- bench-options]

πŸ¦‹ DESCRIPTION πŸ¦‹

okay so. cargo bench compiles your benchmarks and then runs them. that's the whole plot. ✨

here's the arg tea though: the benchmark filtering argument benchname and all the arguments following the two dashes (--) get passed to the benchmark binaries, and therefore to libtest β€” that's rustc's built-in unit-test and micro-benchmarking framework, in case you were wondering who's actually running these things. and if you're passing arguments to both Cargo and the binary? the ones after -- go to the binary, the ones before go to Cargo. simple as that, no cap.

for the full details about libtest's arguments, go peek at 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. πŸ“š

for example, this one runs only the benchmark named foo (and skips other similarly named benchmarks like foobar, sorry 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. 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. πŸ’…

and if you want the libtest harness gone? you can disable it by setting harness = false in the target manifest settings. in that case your code needs to provide its own main function to handle running benchmarks. you're on your own, main character. 😭

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. but if you need to debug a benchmark, you can use the --profile=dev command-line option to switch to the dev profile β€” and then you can run the debug-enabled benchmark within a debugger. obsessed with the flexibility honestly. πŸ”₯

🧚 Working directory of benchmarks 🧚

the working directory of every benchmark is set to the root directory of the package the benchmark belongs to. why does that matter? 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 executed from. it's giving consistency. it's giving reliability. ✨


πŸ‘‘ OPTIONS πŸ‘‘

πŸ”₯ Benchmark Options πŸ”₯

  • --no-run β€” compile, but don't run benchmarks. build only, no cardio. πŸ’…
  • --no-fail-fast β€” run all benchmarks regardless of failure. without this flag, Cargo will exit after the first executable fails. heads up though: the Rust test harness will run all benchmarks within the executable to completion anyway β€” this flag only applies to the executable as a whole. so it's an exe-level thing, not a per-benchmark thing. 🫑

πŸ“ 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.

the default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. and 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. see cargo-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.
  • --workspace β€” benchmark all members in the workspace. the whole squad. πŸ‘‘
  • --all β€” deprecated alias for --workspace. it's still here, it still works, but like... use --workspace. πŸ’€
  • --exclude *SPEC*… β€” exclude the specified packages. must be used in conjunction with the --workspace flag. this flag may be specified multiple times and supports common Unix glob patterns like *, ? and []. and again, 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 or lose it 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 benchmarks
  • bins (only if benchmark targets are built and required features are available)
  • lib as a benchmark
  • bins as 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. but here's the 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. periodt. πŸ’…

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. 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. πŸ™ˆ

  • --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 the test = true manifest 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 the test flag 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 the bench = true manifest 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 the bench flag in the manifest settings for the target.
  • --all-targets β€” benchmark all targets. this is equivalent to specifying --lib --bins --tests --benches --examples. the everything bagel. πŸ₯―

πŸ’œ 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.

  • -F features, --features features β€” space or comma separated list of features to activate. features of workspace members may be enabled with package-name/feature-name syntax. this flag may be specified multiple times, which enables all specified features. stack 'em up. ✨
  • --all-features β€” activate all available features of all selected packages.
  • --no-default-features β€” do not activate the default feature of the selected packages.

⭐ Compilation Options ⭐

  • --target triple β€” benchmark for the given architecture. the default is the host architecture. the general format of the triple is <arch><sub>-<vendor>-<sys>-<abi>. run rustc --print target-list for 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/reference/build-cache.html) documentation for more details.

  • --profile name β€” benchmark with the given profile. see the reference (https://doc.rust-lang.org/cargo/reference/profiles.html) for more details on profiles.
  • --timings=fmts β€” output information on how long each compilation takes, and track concurrency information over time. accepts an optional comma-separated list of output formats; --timings without 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 bestie. It writes a human-readable file called cargo-timing.html into the target/cargo-timings directory, and that file is a whole report of the compilation. It also drops a report in that same directory with a timestamp in the filename, so if you wanna go back and look at older runs you totally can. πŸ’… Heads up tho: HTML output is for human consumption only β€” it does not give you machine-readable timing data, so don't try to parse it, it's giving ✨aesthetic✨ not ✨data✨.
  • json β€” unstable, needs -Zunstable-options. This one emits machine-readable JSON info about the timing information. Perfect for when you want a robot to read it instead of your eyeballs. πŸ€–

πŸ’Ύ Output Options πŸ’Ύ

  • --target-dir directory β€” the directory where all the generated artifacts and intermediate files live. You can also set this with the CARGO_TARGET_DIR environment variable, or via the build.target-dir config value (https://doc.rust-lang.org/cargo/reference/config.html). If you don't say anything, it defaults to target in the root of the workspace. 🎯

🌸 Display Options 🌸

okay so by default the Rust test harness hides the output from benchmark execution, because they want the results to stay readable and not be a whole wall of chaos. But if you do want that output back (say, for debugging, no judgement), you can recover it by passing --nocapture to the benchmark binaries like this:

cargo bench -- --nocapture
  • -v, --verbose β€” use verbose output. And yes you can say it twice for "very verbose" output, which includes extra stuff like dependency warnings and build script output. May also be specified with the term.verbose config value (https://doc.rust-lang.org/cargo/reference/config.html). πŸ—£οΈ
  • -q, --quiet β€” do not print cargo log messages. May also be specified with the term.quiet config value (https://doc.rust-lang.org/cargo/reference/config.html). 🀫
  • --color when β€” controls when colored output is used. The valid values are:
    • auto (the default): automatically detect 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-format fmt β€” the output format for diagnostic messages. You can specify it multiple times, and it takes comma-separated values. Valid values:
    • human (the default): display in a human-readable text format. Conflicts with short and json. πŸ™‹
    • short: emit shorter, human-readable text messages. Conflicts with human and json.
    • 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 with human and short. πŸ€–
    • json-diagnostic-short: make sure the rendered field of JSON messages contains the "short" rendering from rustc. Cannot be used with human or short.
    • json-diagnostic-rendered-ansi: make sure the rendered field of JSON messages contains embedded ANSI color codes so rustc's default color scheme is respected. Cannot be used with human or short. 🌈
    • json-render-diagnostics: tells Cargo to not 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 and the others coming from rustc are still emitted. Cannot be used with human or short.

πŸ“œ Manifest Options πŸ“œ

  • --manifest-path path β€” the path to the Cargo.toml file. By default, Cargo goes looking for the Cargo.toml file in the current directory or any parent directory. πŸ”
  • --ignore-rust-version β€” ignore the rust-version specification in packages. πŸ™ˆ
  • --locked β€” asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of these scenarios pops up:
    • 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 you want deterministic builds, like in CI pipelines. πŸ‘‘

  • --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 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 the cargo-fetch(1) command 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 --locked and --offline. Two-for-one special fr fr. ❄️
  • --lockfile-path PATH β€” changes the path of the lockfile from the default (<workspace_root>/Cargo.lock) to PATH. PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock). Note that providing --lockfile-path will 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 to cargo begins with +, it gets interpreted as a rustup toolchain name (like +stable or +nightly). See the rustup documentation (https://rust-lang.github.io/rustup/overrides.html) for more info on how toolchain overrides work. 🧚
  • --config KEY=VALUE or PATH β€” overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=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. βš™οΈ
  • -C PATH β€” 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, like cargo -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. πŸ’–
  • -Z flag β€” unstable (nightly-only) flags to Cargo. Run cargo -Z help for details. πŸ‘€

πŸŽ€ Miscellaneous Options πŸŽ€

okay this part is 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. So like… one lane only bestie, no carpooling. πŸš—

  • -j N, --jobs N β€” number of parallel jobs to run. May also be specified with the build.jobs config 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 string default is provided, it sets the value back to defaults. Should not be 0. πŸ™…

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

🌈 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 ✨

  1. Build and execute all the benchmarks of the current package:
cargo bench
  1. Run only a specific benchmark within a specific benchmark target:
cargo bench --bench bench_name -- modname::some_benchmark

πŸ‘‘ SEE ALSO πŸ‘‘

cargo(1), cargo-test(1)


and that's the whole thing bestie, you made it to the end of CARGO-BENCH(1) 🫢 go forth and benchmark slay, ily, bye πŸ’…βœ¨

πŸ“¦ where this page comes from