What -O and -O2 optimization do?

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
suhendry
New poster
Posts: 14
Joined: Sat Aug 31, 2002 6:55 am

What -O and -O2 optimization do?

Post by suhendry »

I wonder what kind of optimization does GNU C/C++ do with -O1 and -O2. I do some googling but still can't get the clear idea about the optimization detail.

Code: Select all

int p = 0;
for ( int i = 0; i < 1000000000; i++ )
for ( int j = 0; j < 1000000000; j++ )
for ( int k = 0; k < 1000000000; k++ ) p += i * 5;
If you compile the code using GCC with optimization (-O) and run it, you will get the result in instant! no matter how many nested loop are there. This kinda amazing :D

I wonder how do they work (the optimization)?

and why most of (if not all) online-judges that I know use -O2 optimization? is there any reason for this?
Suhendry Effendy
andmej
Experienced poster
Posts: 158
Joined: Sun Feb 04, 2007 7:45 pm
Location: Medellin, Colombia

Re: What -O and -O2 optimization do?

Post by andmej »

Don't get too excited. Since your program doesn't print anything, g++ removes what he considers "dead-code" and throws away your loops like they were rotten fruit.

You can see the generated Assembly code for a C++ code by adding the flag -S to the compile-line parameters. You will see that compiling your program with -O3 actually makes it do nothing at all.
Runtime errors in Pascal are reported as Wrong Answers by the online judge. Be careful.

Are you dreaming right now?
http://www.dreamviews.com
Post Reply

Return to “C++”