Modify Arduino Optimization Levels on the Fly

fly

Do you know and understand how compiler optimization is altering your code? Higher optimization levels can reveal problems in some programs that are not apparent at lower optimization levels.

Volatility

One method to prevent optimization issues with variables is to declare them as volatile. The declaration of a variable as volatile tells the compiler that the variable can be modified at any time externally to the implementation, for example, by the operating system, by an interrupt handler, or by hardware. Because the value of a volatile-qualified variable can change at any time, the actual variable in memory must always be accessed whenever its referenced in code. This means the compiler cannot perform optimizations on the variable.

Non-Optimum

Another method is to compare versions of your code with different levels of optimization. You may not realize that changing the optimization level of your code is actually very easy once you know how. Here are two techniques to change the optimization level on the fly.

Pragma-tic Programming

To change optimization for large areas of code, I recommend using the optimize pragma. Surrounding the code with the push and pop option pragma is also a good practice. Here is an example:


#pragma GCC optimize ("-O0")
#pragma GCC push_options

void setup() { }
void loop() { }

#pragma GCC pop_options

Know Your Attributes

If you want to effect the optimization of just a single function, use the optimize attribute like so:


void loop() __attribute__((optimize("-O0")));
void loop() { }

References

More information on GCC optimization can be found here.
More information on GCC function attributes can be found here.
More information on GCC pragmas can be found here.

Advertisements

About Jim Eli

µC experimenter
This entry was posted in arduino, avr and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s