首页 > 解决方案 > turn off c++ loop optimization

问题描述

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.

标签: c++loopsoptimizationmicrobenchmark

解决方案


您可以使用类似 Google Benchmark 的DoNotOptimize()功能。该函数使用一个空asm块来欺骗从读取给定变量的编译器。改编自这里

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
}

然后,您可以对编译器撒谎并告诉它res在每次迭代中读取的内容:

#include <iostream>

int main ()
{
    int res = 0;

    ::DoNotOptimize(res);
    for (long i = 0; i < 10; i++)
    {
        res++;
        ::DoNotOptimize(res);
    }
    std::cout << res;
}

编译器资源管理器链接

-O3中,循环展开,但-O1保持-O2循环。


推荐阅读