Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any drawbacks to using -O3 in GCC?

Tags:

c++

c

gcc

I've been a Software Engineer for 13 years in various languages, though I'm just now making my way into C and later C++. As I'm learning C, I'm using the GCC compiler to compile my programs, and I'm wondering if there are any gotchas to using -O3 or other optimization flags. Is there a chance that my software will break in ways that I won't be able to catch without testing the compiled code, or perhaps during cross-compilation, I might inadvertently mess something up for a different platform.

Before I blindly turn those options on, I'd like to know what I can expect. Also, as -Ofast turns on non-standards-compliant flags, I'm leaning towards not using that. Am I correct in my assumptions that -Ofast will most likely have "side-effects?"

I've glanced over https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html before I posted this question.

like image 808
Rick Mac Gillis Avatar asked Dec 13 '15 01:12

Rick Mac Gillis


2 Answers

The only drawback of -O3 should be the inability to follow the code in a debugger.

The use of -Ofast can affect some of your floating point operations causing rounding errors, but unless you are running specifically long chains of floating point calculations you are unlikely to ever notice.

Broken code (code with bad pointers or statements with undefined behavior) is likely to behave differently at different level of optimization -- the first reaction of many programmers is to blame the compiler -- enabling all warnings and fixing them usually helps.

like image 156
Soren Avatar answered Sep 18 '22 20:09

Soren


It's important to remember that almost all compiler optimizations are heuristics. In other words, an "optmization" is only an attempt to make your program more "optimal", but it could very well have the opposite effect. Just because -O3 is supposed to be better than -O2, and -O2 should be better than -O1—that doesn't mean that is in fact always how it works.

Sometimes an "optimization" enabled by -O3 might actually slow your program down when compared with the version generated with -O2 or -O1. You should experiment with different levels of optimization to see what works best for your specific code. You can even turn individual optmizations on and off if you really want to fine-tune it.

So in short—yes, there can be downsides to using -O3. I have personally observed that a lot of stuff I've written works better with -O2 than with -O3—but that's really program-specific.


FYI, here's another SO question that's asking why -O2 gives better results than -O3 for a specific program: gcc optimization flag -O3 makes code slower then -O2

like image 22
DaoWen Avatar answered Sep 17 '22 20:09

DaoWen