Compiling in GCC: Is -O3 harmful?

I heard that it is not possible to compile with the -O3 option with gcc. It's true? If so, what are the reasons for excluding -O3?

+3


source to share


1 answer


Answer: it depends on your code.

The basic rule of thumb is:

  • In -O1, the compiler makes optimizations that don't take too long to compute.

  • In -O2, the compiler makes "expensive" optimizations that can slow down the compilation process. They can also make the output program a little larger, but probably not much.

  • -Os is about the same as -O2, but the optimization is tuned more than the speed. For the most part, the two functions do not conflict (more optimal code takes fewer steps and therefore fewer steps), but there are some tricks that duplicate code to avoid branching penalties, for example.

  • At -O3, the compiler actually runs the space optimization. It will be built into functions much more aggressively, and try to use vectorization where possible.

You can find more details in the GCC documentation . If you really want to optimize your code, then you can try to include even more options not used even with -O3; -floop-*

, eg.

The problem with space-speed optimizations, in particular, is that they can negatively impact the efficiency of your memory caches. The code may be better for the CPU, but if it's not better for your memory, you will lose. For this reason, if your program does not have a single hotspot where it spends all this time, you may find that it slows down in general.



Optimization in the real world is an imprecise science for three reasons:

  • User equipment varies greatly.

  • What's good for one codebase may not be good for another.

  • We want the compiler to be fast, so it should make the best guess, not try to use all the options and pick the best.

Basically, the answer is always, if performance matters , try all levels of optimization, determine how well your code works, and choose the best one for you . And do it again with every big change.

If performance doesn't matter, -O2 is the choice for you.

+4


source







All Articles