Profiling a library project

Hello there!
i'm new to Rust and i was wondering how to run some profiling on my library project. In particular, I can't figure out with what i should feed the profiler if i don't have any exec/main. I've been trying to use the CLion built-in profiler to profile unit tests without getting good results.

You could create benchmarks with criterion (or a less featureful benchmarking crate).

Hello! For profiling, I recommend benchmarking your code with a library like criterion. It is similar to unit testing but tracks how long running a specific function takes, not whether the output is correct.

We literally answered at the same time. (Or almost).


1 Like

Lol I saw :smiley:

Then I should feed the profiler with the bin generated by the cargo bench, shouldn't I?

You basically create something like tests for specific functions (or benches as they are called). Criterion does execute does and provide you with a lot of information about the execution time of such a 'benched" function.

I guess the real question is "if I want to have a more fine-grained timing then just the time of test" (e.g. flamegraph), what executable should be run under perf or similar?

1 Like

Yes, i've already executed some benches using criterion. Now i would like to do real profiling (e.g. finding hot spots in the code within my library) and my problem is the one you mentioned.

You could either try to find the test executables that cargo created in the target folder (if this is what cargo does when one calls cargo test) and use prof on this executable.

Or you create an example executable (e.g. in an example folder) and you use prof on this executable.

I've tried to use the profiler on the executable generated by the compilation of an example i created in the examples folder. The problem is that i can't see any useful information in the flamegraph.

IDEA: Could it be due to the fact that, since i'm running the function i want to profile with a constant value as argument, the compiler is optimizing the whole function swapping it with a precomputed value? Similar problem fixed by using black_box in Criterion.

As far as I understand you: the flame graph you created with your example does not show your function, am I right?

You could try to mark your function with the attribute #[inline(never)]. Although I am not sure if the compiler needs to follow this attribute strictly.

Another option is to add a command line argument to your example (the crate clap comes to mind) and this command line argument is fit into your example executable. I would assume that the compiler is not able to optimize in this case.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.