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)
source share