I am wondering how to turn off optimization for the following loop. I have searched and tried some flag but not working. Thanks.
#include <iostream>
int fun(int i) {return ++i;};
int main ()
{
int res = 0;
for (long i = 0; i < 10000; i++)
{
res += fun(i);
}
std::cout << res;
}
-O1 will remove the loop and directly hard code the result. I would like to use -O3 but with this optimization turned off.
You can use something like Google Benchmark's DoNotOptimize()
function. This function uses an empty asm
block to lie to the compiler that the given variable was read from. Adapted from here:
template <class Tp>
[[gnu::always_inline]] inline void DoNotOptimize(Tp const& value) {
asm volatile("" : : "r,m"(value) : "memory");
}
template <class Tp>
[[gnu::always_inline]] inline void DoNotOptimize(Tp& value) {
#if defined(__clang__)
asm volatile("" : "+r,m"(value) : : "memory");
#else
asm volatile("" : "+m,r"(value) : : "memory");
#endif
}
Then, you can lie to the compiler and tell it that res
is read in each iteration:
#include <iostream>
int main ()
{
int res = 0;
::DoNotOptimize(res);
for (long i = 0; i < 10; i++)
{
res++;
::DoNotOptimize(res);
}
std::cout << res;
}
In -O3
, the loop is unrolled, but -O1
and -O2
keep the loop.