I've been trying to read through the MSDN pages on the various optimization flags.
We currently have most of our projects set to /O2
which optimizes for "maximize speed".
My confusion is what exactly this means. Which of the following statements are closer to true regarding the /O2
flag?
I made the argument that we should use the /Ox
flag, but that was when I was under the impression that Option 2 was true.
I was basically told "we're not going to change from /O2
to /Ox
unless someone has solid evidence that we need to do so".
So my question is does /O2
still perform memory optimizations? E.g. return value optimization, copy elision, etc. What would we gain from switching from /O2
to /Ox
?
-O2 Optimize even more. GCC performs nearly all supported optimizations that do not involve a space-speed tradeoff. The compiler does not perform loop unrolling or function inlining when you specify -O2. As compared to -O, this option increases both compilation time and the performance of the generated code.
-O3 instructs the compiler to optimize for the performance of generated code and disregard the size of the generated code, which might result in an increased code size. It also degrades the debug experience compared to -O2 .
By optimizing an executable, you can achieve a balance between fast execution speed and small code size. This topic discusses some of the mechanisms that Visual Studio provides to help you optimize code.
As Arkanosis pointed out correctly, when going from /O2 to /Ox, you disable /Gs, /GF, /Gy. The question is which of these flags may increase execution speed?
/Gs is identical to /Gs0 and can have negative impact on performance. See below the description on MSDN.
activates stack probes for every function call that requires storage for local variables. This can have a negative impact on performance
/GF eliminates duplicate strings (constants) - called string pooling. This will reduce the code size. A lower code could produce lower number of instruction cache misses but I doubt this effect is observable on most codes.
/Gy flag alows packaging individual functions into COMDAT structures. These can be used as a workaround to avoid compile time errors due to multiple definitions of the same symbol. The MSDN documentation states that this just affects build time but not the execution time. They generally recommend using it.
Conclusion:
/Ox disables /Gs, /GF, /Gy. In some cases, these options hurt performance and almost never improve execution speed, compared with /O2. Of course they have benefits but not related to speed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With