简体   繁体   中英

Disabling specific optimization(Dead code elimination) in gcc compiler

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?

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(); 

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..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM