[ACCEPTED]-When to use -O2 flag for gcc?-gcc

Accepted answer
Score: 26

I would recommend using -O2 most of the 7 time, benefits include:

  • Usually reduces size of generated code (unlike -O3).
  • More warnings (some warnings require analysis that is only done during optimization)
  • Often measurably improved performance (which may not matter).

If release-level 6 code will have optimization enabled, it's 5 best to have optimization enabled throughout 4 the development/test cycle.

Source-level 3 debugging is more difficult with optimizations 2 enabled, occasionally it is helpful to disable 1 optimization when debugging a problem.

Score: 11

I'm in bioinformatics so my advice may be 12 biased. That said, I always use the -O3 switch (for 11 release and test builds, that is; not usually 10 for debugging). True, it has certain disadvantages, namely 9 increasing compile-time and often the size 8 of the executable.

However, the first factor 7 can be partially mitigated by a good build 6 strategy and other tricks reducing the overall 5 build time. Also, since most of the compilation 4 is really I/O bound, the increase of compile 3 time is often not that pronounced.

The second 2 disadvantage, the executable's size, often 1 simply doesn't matter at all.

Score: 6

Never.

Use -O3 -Wall -Werror -std=[whatever 1 your code base should follow]

Score: 5

Always, except when you're programming and 1 just want to test something you just wrote.

Score: 3

We usually have our build environment set 9 up so that we can build debug builds that use -O0 and 8 release builds that use -O3 (the build enviroment preserves 7 the objects and libraries of all configurations, so 6 that one can switch easily between configurations). During 5 development one mostly builds and runs the 4 debug configuration for faster build speed 3 (and more accurate debug information) and 2 less frequently also builds and tests the 1 release configuration.

Score: 2

Is the increased compilation time really 10 noticable? I use -O2 all the time as the 9 default, anything less just leaves a lot 8 of "friction" in your code. Also note 7 that the optimization levels of -O1, -O2 6 tends to be the best tested, as they are 5 most interesting. -O0 tends to be more buggy, and 4 you can debug pretty well at -O2 in my experience. Provided 3 you have some idea about what a compiler 2 can do in terms of code reordering, inlining, etc.

-Werror 1 -Wall is necessary.

More Related questions