App note: Tips and tricks to optimize your C code for 8-bit AVR microcontrollers

apps

An application note (PDF!) on code optimization in AVR microcontrollers from Atmel :

Features
• Atmel® AVR® core and Atmel AVR GCC introduction
• Tips and tricks to reduce code size
• Tips and tricks to reduce execution time
• Examples application

AVR core is an advanced RISC architecture tuned for C code. It ensures the development of good products with more features at less cost.
When talking about optimization, we usually refer to two aspects: code size and code speed. Nowadays, C compilers have different optimization options to help developers get an efficient code on either size or speed.

Join the Conversation

5 Comments

  1. I would suggest anyone reading that app note to take the advice with a grain of salt, and experiment for themselves. Eg. the tip in the screenshot will produce identical code for both cases. The usual caveats about optimization also apply: first make your program correct, then measure and only optimize where it matters. With modern compilers that is in fewer places than you think, and obfuscating your code for micro-optimizations is rarely a tradeoff worth making.

  2. On the other hand it shows the sad state of the compiler.

    Optimizing this simple count loop (no inside loop access to counter) should be a piece of cake.

    Apparently it does not. Older ppl. will remember those days with FORTAN and COBOL. Not learned much.

  3. Agreed—the coder should always code in the most intuitive, understandable way possible, and then, only if the code is demonstrably too slow, optimize only the problematic parts. (“Premature optimization” is a well-enough-known anti-pattern that it has a name.) If extremely common idioms such as this simple loop aren’t automatically optimized, the compiler isn’t doing its job.

  4. Seems a bit out of date.

    I’ve tried both examples with GCC 4.8.2, with -Os optimization. Both yield the same machinecode.

    So, I’ve also tried the (simple) way how I would write a loop:

    int main(void)
    {
    uint8_t local_1;
    for (local_1=0; local_1< 100; local_1++) {
    PORTB ^= 0x01;
    }
    }

    Also the same binary.

    Seems that the current gcc is pefectly capable of optimizing this….

  5. PDF is from 2011-11-10, gcc they used is 4.5.1.

    My FORTRAN is from 1968. Long way to learn such little things.

Leave a comment

Your email address will not be published. Required fields are marked *

Notify me of followup comments via e-mail. You can also subscribe without commenting.