问题
I have some legacy code where a timewasting loop has been included to allow time for an eeprom read to complete (bad practice):
for(i = 0; i < 50; i++);
However, peculiar things happen when compiler optimizations are switched on for speed. It is not necessarily connected with that statement, but I would like to know if the compiler might just optimize the time delay away
回答1:
It depends on the type of i
. If it is just a plain integer type that isn't used apart from inside the loop, there are no side effects and the compiler is free to optimize away the whole thing.
If you declare i
as volatile
however, the compiler is forced to generate code that increments the variable and reads it, at each lap of the loop.
This is one of many reasons why you should not use "burn-away" loops like these in embedded systems. You also occupy 100% CPU and consume 100% current. And you create a tight coupling between your system clock and the loop, which isn't necessarily linear.
The professional solution is always to use an on-chip hardware timer instead of "burn-away" loops.
回答2:
Lundin answer explains why it happens properly, so no need to paraphrase.
That said, if you really need to keep the old behaviour in your loop but optimize the rest, the easiest way would be to put 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 build this file without any optimizing flags on.
Build the rest of your code with optimizing flags on to benefit from optimizer on "normal" code.
Note that because of function call overhead and the very short execution time of the loop, the delay slightly increases when moving from inline call to a function in a separate object file.
You may want to reduce d
value to match previous timing (if it's necessary)
来源:https://stackoverflow.com/questions/42415271/c-how-would-compiler-optimization-affect-a-for-loop-with-no-body