C - how will compiler optimization affect a for loop without a body?

I have legacy code that includes a timewasting loop to give eeprom time to read (bad practice):

for(i = 0; i < 50; i++); 

However, special features arise when compiler optimization is turned on for speed. This is not necessarily related to this statement, but I would like to know if the compiler can simply optimize the delay time.

+5
source share
2 answers

It depends on type i . If it is just a simple integer type that is not used separately from the loop, there are no side effects, and the compiler is free to optimize all of this.

If you declare i as volatile , however, the compiler is forced to generate code that increments this variable and reads it on each lap of the loop.

This is one of many reasons why you shouldn't use loops like in embedded systems. You also occupy 100% of the processor and consume 100% of the current. And you create a tight connection between your system clock and the cycle, which is not necessarily linear.

A professional solution should always use a built-in hardware timer instead of “burn” cycles.

+13
source

Lundin's answer explains why this happens correctly, so there is no need to rephrase.

However, if you really need to keep the old behavior in your loop, but optimize the rest, the easiest way would be to include this active delay loop in one function in one file:

 #include <active_delay.h> // the corresponding header file void active_delay(int d) { // do not build with optimize flags on! int i; for(i = 0; i < d; i++); } 

and create this file without any optimization flags.

Build the rest of the code using flag optimization to use the optimizer for “normal” code.

Please note that due to the overhead of the function call and the very short execution time of the cycle, the delay increases slightly when switching from the built-in call to the function in a separate object file.

You can decrease the d value to match the previous time (if necessary)

+8
source

Source: https://habr.com/ru/post/1264624/


All Articles