CARGO-BENCH(1)

πŸ“¦ version 1.95.0, in ubuntu stonking

πŸ’– 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. 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. 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 --workspace flag. 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 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. 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, --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 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.

  • -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. 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 ⭐

  • --target triple β€” 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.
  • --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 β€” 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-dir directory β€” this is the home for literally every generated artifact and intermediate file. You can also set it 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 say nothing at all, it defaults to target in 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 the term.verbose config 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 the term.quiet config value (https://doc.rust-lang.org/cargo/reference/config.html).
  • --color when β€” 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-format fmt β€” 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 with short and json.
    • short: emits shorter, human-readable text messages. Conflicts with human and json.
    • 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 with human and short.
    • json-diagnostic-short: makes sure the rendered field of JSON messages contains the "short" rendering straight from rustc. Cannot be used with human or short.
    • json-diagnostic-rendered-ansi: makes 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 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 with human or short.

πŸ“œ Manifest Options πŸ“œ

  • --manifest-path path β€” the path to the Cargo.toml file. If you don't give one, Cargo goes hunting for Cargo.toml in the current directory, and then in every parent directory above it. She's thorough πŸ’…
  • --ignore-rust-version β€” ignores the rust-version specification in packages. YOLO.
  • --locked β€” this one 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 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 --locked and --offline. Two for one, slay.

πŸ› οΈ Common Options πŸ› οΈ

  • +toolchain β€” if Cargo was installed with rustup, and the first argument to cargo starts with +, it gets interpreted as a rustup toolchain name (things like +stable or +nightly). The rustup documentation (https://rust-lang.github.io/rustup/overrides.html) has more on how toolchain overrides work.
  • --config KEY=VALUE or PATH β€” overrides a Cargo configuration value. The argument should be in TOML syntax as KEY=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.
  • -C PATH β€” 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, 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 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.
  • -Z flag β€” unstable (nightly-only) flags for Cargo. Run cargo -Z help for 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. πŸ‘‘

  • -j N, --jobs N β€” the number of parallel jobs to run. Can also be set with the build.jobs config 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 string default, it resets the value back to the defaults. And it should not be 0. 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 πŸ’–

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