c++ - 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.
解决方案
您可以使用类似 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
循环。
推荐阅读
- php - Htaccess重定向重复和HTML链接问题
- excel - 将调试数据写入新工作表上的新表
- javascript - 当我使用后退按钮导航时,useEffect 未执行
- angular - 其他模块中的图表
- javascript - 如何在Javascript中实现刷新状态?
- node.js - 子目录中的 Nuxtjs 和 Nginx 反向代理
- javascript - 尝试在 edureka 上复制 API 教程
- javascript - Google Analytics(分析)客户端 ID 不会进入我表单的隐藏字段
- java - 从前台服务更新 Singleton 成员属性
- python - Python Azure 函数 - 使用 Key Vault 进行 MSI 身份验证