rustrust-cargo

How do I run cargo flamegraph on unit-tests in lib crate


I have a library crate which I want to profile using cargo flamegraph. But however I try to run cargo flamegraph, I get error messages. The library has the following structure:

utilrs
├── Cargo.lock
├── Cargo.toml
└── src
    ├── fileprocessor.rs
    ├── filesplit.rs
    ├── forwardstar.rs
    ├── lib.rs
    ├── persistence.rs
    └── xmlparser.rs

What I am looking for is to exectue a test called split_and_process_file within a tests module within the fileprocessor.rs file.

I tried different command line combinations, but they all resulted in errors. Some of the things I tried are:

cargo flamegraph --unit-test -- fileprocessor::tests::split_and_process_file resulting in :Error: crate has no automatically selectable target

and

cargo flamegraph --unit-test utilrs -- fileprocessor::tests::split_and_process_file resulting in error: no bin target named `utilrs`.

System Information: |Component | Version| |----------|--------| |Operating System|Windows 10, 64-bit| |cargo |cargo 1.65.0-nightly (4ed54cecc 2022-08-27)| |rustc|rustc 1.65.0-nightly (84f0c3f79 2022-09-03)|


Solution

  • As the error indicates: error: no bin target named 'split_and_process_file', there is no bin target.

    A target for cargo is something like lib, bin, etc. That said, there is no such called split_and_process_file function in your main.rs file.

    Oops, you don't have main.rs, then you should create one and add your function. Then, run flamegraph with your bin files.. Don't forget to use the --release with cargo run.

    As the flamegraph crate page says:

    by default, --release profile is used, but you can override this: cargo flamegraph --dev

    If you still want to use a lib but not a bin, then use the --dev thingy.