Skip to content

Tip: Understanding memory usage with the compiler optimizer #9

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
philj404 opened this issue Jun 6, 2021 · 0 comments
Open

Tip: Understanding memory usage with the compiler optimizer #9

philj404 opened this issue Jun 6, 2021 · 0 comments

Comments

@philj404
Copy link

philj404 commented Jun 6, 2021

(I am pulling out this comment from #3 as its own topic as I think it will be helpful.)

After compiler optimization many expected side effects can disappear:

  • aggressive inlining of functions means the stack pointer may never change with a function call. This can be useful if RAM space is small, and there is plenty of ROM for code -- like for the AVR architecture.
  • the compiler may keep variables in registers, so again the stack pointer may never need to change
  • the compiler seems to detect "unused/unchanged" values and not bother generating code for them.

This is all good in principle. But the optimizations make it difficult to predict how much stack space is needed, just by inspection. Even for a simple example. Often nothing seems to change, especially for simple examples.

I was able to get more predictable results by:

  • declaring functions noinline, for example void __attribute__ ((noinline)) myStackUsingFunction(void) {...};. This ensures the function call will exercise the stack so this library can observe it.
  • declaring variables volatile, which hints to the compiler it should manipulate the variable (and put it on the stack), even if it seems unnecessary.

Note that noinline and volatile declarations make memory usage more predictable, but less efficient. It may be useful while you are still debugging your code. Once you are done debugging your memory allocations, you might want to take the declarations out so the optimizers can help free up RAM storage.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant