Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use -O2 flag for gcc?

If I use "-O2" flag, the performance improves, but the compilation time gets longer.

How can I decide, whether to use it or not?

Maybe O2 makes the most difference in some certain types of code (e.g. math calculations?), and I should use it only for those parts of the project?

EDIT: I want to emphasize the fact that setting -O2 for all components of my project changes the total compilation time from 10 minutes to 30 minutes.

like image 380
Igor Avatar asked May 20 '09 11:05

Igor


People also ask

What is the purpose of the flag when using GCC?

By default, GCC limits the size of functions that can be inlined. This flag allows the control of this limit for functions that are explicitly marked as inline (i.e., marked with the inline keyword or defined within the class definition in c++).

What is the purpose of the flag when compiling?

Compile-time flags are boolean values provided through the compiler via a macro method. They allow to conditionally include or exclude code based on compile time conditions. There are several default flags provided by the compiler with information about compiler options and the target platform.

Which GCC flag is used to generate?

gcc -g generates debug information to be used by GDB debugger.

What is GCC wall flag?

gcc -Wall enables all compiler's warning messages. This option should always be used, in order to generate better code.


3 Answers

I would recommend using -O2 most of the 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 code will have optimization enabled, it's best to have optimization enabled throughout the development/test cycle.

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

like image 146
Lance Richardson Avatar answered Oct 21 '22 01:10

Lance Richardson


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

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

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

like image 21
Konrad Rudolph Avatar answered Oct 21 '22 01:10

Konrad Rudolph


Never.

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

like image 40
Christoffer Avatar answered Oct 21 '22 03:10

Christoffer