Search code examples
ruststack-memory

How to measure a functions stack usage in Rust?


Is there a way I can measure how much stack memory a function uses?

This question isn't specific to recursive functions; however I was interested to know how much stack memory a function called recursively would take.

I was interested to optimize the function for stack memory usage; however, without knowing what optimizations the compiler is already making, it's just guess-work if this is making real improvements or not.

To be clear, this is not a question about how to optimize for better stack usage.

So is there some reliable way to find out how much stack memory a function uses in Rust?


Note that other compilers support this, GCC has -fstack-usage for example.


Solution

  • As of today there are some experimental tools to estimate stack usage: https://crates.io/crates/cargo-call-stack It uses experimental -Z emit-stack-sizes to get the stack for each function, and then manage to extract the call graph and from there generate the worst case estimation