How to measure a functions stack usage in C?

ideasman42 picture ideasman42 · Feb 12, 2015 · Viewed 9.2k times · Source

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


Note: Assuming it's not using alloca or variable-length arrays, it should be possible to find this at compile time.

Answer

ideasman42 picture ideasman42 · Feb 13, 2015

Using warnings

This is GCC specific (tested with gcc 4.9):

Add this above the function:

#pragma GCC diagnostic error "-Wframe-larger-than="

Which reports errors such as:

error: the frame size of 272 bytes is larger than 1 bytes [-Werror=frame-larger-than=]

While a slightly odd way method, you can at least do this quickly while editing the file.

Using CFLAGS

You can add -fstack-usage to your CFLAGS, which then writes out text files along side the object files. See: https://gcc.gnu.org/onlinedocs/gnat_ugn/Static-Stack-Usage-Analysis.html While this works very well, its may be a little inconvenient depending on your buildsystem/configuration - to build a single file with a different CFLAG, though this can of course be automated. – (thanks to @nos's comment)


Note,

It seems most/all of the compiler natural methods rely on guessing - which isn't 100% sure to remain accurate after optimizations, so this at least gives a definitive answer using a free compiler.