How to prevent GCC from optimizing out a busy wait

2019-01-04 08:22发布

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 (-Os or -O2), as I see no reason to not enable them, and they will probably generate a better assembly way faster than writing assembly manually.

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.

/* How to NOT optimize this, while optimizing other code? */
unsigned char i, j;
j = 0;
while(--j) {
    i = 0;
    while(--i);
}

Since memory access in AVR is a lot slower, I want i and j to be kept in CPU registers.


Update: I just found util/delay.h and util/delay_basic.h from AVR Libc. Although most times it might be a better idea to use those functions, this question remains valid and interesting.


Related questions:

8条回答
神经病院院长
2楼-- · 2019-01-04 09:15

I don't know off the top of my head if the avr version of the compiler supports the full set of #pragmas (the interesting ones in the link all date from gcc version 4.4), but that is where you would usually start.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-01-04 09:18

You can also use the register keyword. Variables declared with register are stored in CPU registers.

In your case:

register unsigned char i, j;
j = 0;
while(--j) {
    i = 0;
    while(--i);
}
查看更多
登录 后发表回答