Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will an empty for loop used as a sleep be optimized away? [duplicate]

Tags:

c

I am looking over some code to review and have come across a busy wait as such:

int loop = us*32;
int x;
for(x = 0;x<loop;x++)
{
    /*do nothing*/      
}

I seem to recall reading that these empty loops can be optimized away. Is this what would happen here or can this work?

like image 879
Firedragon Avatar asked Apr 24 '12 14:04

Firedragon


1 Answers

The answer is yes, the compiler can optimize out the loop.

Use the volatile qualifier to avoid the optimization:

int loop = us * 32;
volatile int x;
for (x = 0; x < loop; x++)
{
    /*do nothing*/      
}

If you are programming in the embedded world read the documentation of your compiler as they usually provide delay functions that wait for a certain number of cycles or microseconds passed in parameter.

For example, avr-gcc has the following function in util/delay.h:

void _delay_us(double __us);
like image 199
ouah Avatar answered Oct 30 '22 08:10

ouah