Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between gcc optimization levels?

Tags:

What is the difference between different optimization levels in GCC? Assuming I don't care to have any debug hooks, why wouldn't I just use the highest level of optimization available to me? does a higher level of optimization necessarily (i.e. provably) generate a faster program?

like image 729
rmukhopadhyay Avatar asked Sep 18 '08 05:09

rmukhopadhyay


People also ask

What are the optimization levels in GCC?

-O1 (optimize minimally) -O2 (optimize more) -O3 (optimize even more) -Ofast (optimize very aggressively to the point of breaking standard compliance)

How many levels of optimization are there?

6.4 Optimization levels. In order to control compilation-time and compiler memory usage, and the trade-offs between speed and space for the resulting executable, GCC provides a range of general optimization levels, numbered from 0--3, as well as individual options for specific types of optimization.

What is #pragma GCC optimize O3?

Pragmas are implementation specific but, in this case (gcc), it sets the optimisation level to 3 (high), similar in effect to using -O3 on the command line. Details on optimisation levels for gcc , and the individual flags that get set in response, can be found here.


1 Answers

Yes, a higher level can sometimes mean a better performing program. However, it can cause problems depending on your code. For example, branch prediction (enabled in -O1 and up) can break poorly written multi threading programs by causing a race condition. Optimization will actually decide something that's better than what you wrote, which in some cases might not work.

And sometimes, the higher optimizations (-O3) add no reasonable benefit but a lot of extra size. Your own testing can determine if this size tradeoff makes a reasonable performance gain for your system.

As a final note, the GNU project compiles all of their programs at -O2 by default, and -O2 is fairly common elsewhere.

like image 98
Martin W Avatar answered Oct 11 '22 04:10

Martin W