title: How to prevent GCC from optimizing out a busy wait loop?
body: <p>I want to write a C code firmware for Atmel AVR microcontrollers. I will compile it using GCC. Also, I want to enable compiler optimizations (<code>-Os</code> or <code>-O2</code>), as I see no reason to not enable them, and they will probably generate a better assembly way faster than writing assembly manually.</p>
  
  <p>But I want a small piece of code not optimized. I want to delay the execution of a function by some time, and thus I wanted to write a do-nothing loop just to waste some time. No need to be precise, just wait some time.</p>
  
  <pre><code>/* How to NOT optimize this, while optimizing other code? */
  unsigned char i, j;
  j = 0;
  while(--j) {
      i = 0;
      while(--i);
  }
  </code></pre>
  
  <p>Since memory access in AVR is a lot slower, I want <code>i</code> and <code>j</code> to be kept in CPU registers.</p>
  
  <hr>
  
  <p>Update: I just found <a href="http://www.nongnu.org/avr-libc/user-manual/group__util__delay.html" rel="noreferrer">util/delay.h</a> and <a href="http://www.nongnu.org/avr-libc/user-manual/group__util__delay__basic.html" rel="noreferrer">util/delay_basic.h</a> from <a href="http://www.nongnu.org/avr-libc/" rel="noreferrer">AVR Libc</a>. Although most times it might be a better idea to use those functions, this question remains valid and interesting.</p>
  
  <hr>
  
  <p>Related questions:</p>
  
  <ul>
  <li><a href="https://stackoverflow.com/q/2219829">How to prevent gcc optimizing some statements in C?</a></li>
  <li><a href="https://stackoverflow.com/q/5580140">Is there a way to tell GCC not to optimise a particular piece of code?</a></li>
  <li><a href="https://stackoverflow.com/q/28287064">How not to optimize away - mechanics of a folly function</a></li>
  </ul>