在 gcc 编译器中禁用特定优化(死代码消除)

发布于 2024-12-28 14:09:00 字数 303 浏览 5 评论 0原文

我想在 C++ 编译中禁用死代码消除优化。有没有办法通过保留所有其他 -O 优化来禁用此特定优化。我尝试使用 -fnodce 但它不起作用。

更新(从评论中复制):我有类似的事情,

timer t;
t.start();
for(int i=1;i<=1000;++i)
    object t;
t.stop();

我想测量对象t构建时间并且不对其执行任何操作。我不想通过创建 1000 个对象的数组来实现此目的。有办法解决这个问题吗?

I would like to disable dead code elimination optimization in c++ compilation. Is there a way to disable this particular optimization by keeping all other -O optimization. I tried with -fnodce but its not working.

Update (copied from a comment): I have something like

timer t;
t.start();
for(int i=1;i<=1000;++i)
    object t;
t.stop();

I want to measure object t construction time and do nothing with it. I dont want to do this by creating an array of 1000 objects. Is there a way to solve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

无风消散 2025-01-04 14:09:00

在构造对象上添加“易失性”限定符,这告诉编译器假设构造存在副作用,从而防止对其进行优化。那是:

timer t; 
t.start(); 
for(int i=1;i<=1000;++i) 
  volatile object t; 
t.stop(); 

Add "volatile" qualifier on constructed objects, this tells the compiler to assume that there are side-effects to construction thus preventing optimizing it away. That is:

timer t; 
t.start(); 
for(int i=1;i<=1000;++i) 
  volatile object t; 
t.stop(); 
春花秋月 2025-01-04 14:09:00

好吧,如果您只想测量对象的初始化时间,为什么要尝试强制编译器避免 DCE 之类的东西,而不只是以一开始就避免问题的方式编写它呢?

object *arr = new object[100];   // allocate that outside the function and pass it into it
for (int i = 0; i < 100; i++) {
    arr[i] = new object;
}

如果函数足够大,可以避免内联,那么应该可以很好地实现这一目的 - 否则,您可以导出该函数并从另一个编译模块调用它,以避免不必要的优化。简单,没有一些编译器标志的技巧,可能会产生意想不到的后果,唯一的开销是数组存储 - 如果这明显影响你的时间,无论如何你都会测量错误的东西。

或者,如果您确实想要一些编译器特定的标志 - gcc 有一个 noinline 属性。

Well if you just want to measure the initialization time of your objects why try to coerce the compiler to avoid DCE and whatnot and not just write it in such a way as to avoid the problem in the first place?

object *arr = new object[100];   // allocate that outside the function and pass it into it
for (int i = 0; i < 100; i++) {
    arr[i] = new object;
}

If the function is large enough to avoid inlining that should do the trick just fine - otherwise you can export the function and call it from another compilation module to avoid unwanted optimizations. Simple, no tricks with some compiler flags that may have unintended consequences and the only overhead is an array store - if THAT measurably influences your timing you're measuring the wrong things anyhow.

Or if you really want some compiler specific flags - gcc has a noinline attribute..

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文