gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

C/C++ > Compiler optimization with useless statements

#167411 - Echo49 - Wed Mar 11, 2009 4:37 am

Not really to do with coding, but if I have a simple addition that does nothing:
Code:
for (int i=0;i<A_BIG_NUMBER;++i)
    45+56;

Does the compiler exclude that line from the binary?

#167415 - Ruben - Wed Mar 11, 2009 7:22 am

Depends on the level of optimization.

-O0 will not. This level of optimization does absolutely no optimization and handles the code exactly as you type it.

-O1 may, depending on your compiler.

-O2 most likely will.

If you have -Wall or -Wextra, I can't remember, the compiler will warn you about a loop with no effect.

#167418 - Dwedit - Wed Mar 11, 2009 8:38 am

If you use -S, you can see what the compiler does.
_________________
"We are merely sprites that dance at the beck and call of our button pressing overlord."

#167420 - Echo49 - Wed Mar 11, 2009 9:07 am

I have this code, compiled with -O0 as suggested.
Code:
      for (i=0; i<LOOPS; ++i) {
         54+56;
      }
      
      //...
      
      for (i=0; i<LOOPS; ++i) {
         34+57;87+21;
      }

Why does the first loop take more time to execute (when using the clock() function from time.h) than the second loop? LOOPS is 100,000,000

#167422 - Pete_Lockwood - Wed Mar 11, 2009 1:03 pm

What assembler does it produce? If it's really taking more time, the answer will be there.
_________________
It's not an illusion, it just looks like one.

#167444 - Echo49 - Thu Mar 12, 2009 7:58 am

Curiously enough,
Code:
MOV EAX,DWORD PTR SS:[EBP-20]
MOV DWORD PTR SS:[EBP-20],EAX

takes longer to execute than
Code:
MOV EAX,DWORD PTR SS:[EBP-20]
ADD EAX,1
MOV DWORD PTR SS:[EBP-20],EAX

when both are executed one trillion times.

#167445 - Ruben - Thu Mar 12, 2009 8:33 am

I think it's got to do with the pipeline of the CPU, cos if they were constant timings, the second one should've taken longer.

#167456 - Miked0801 - Thu Mar 12, 2009 4:58 pm

Man I forgot how ugly x86 assembler is to ARM.

#167459 - Kyoufu Kawa - Thu Mar 12, 2009 6:53 pm

Miked0801 wrote:
Man I forgot how ugly x86 assembler is to ARM.
Amen to that.

#167462 - Echo49 - Thu Mar 12, 2009 8:39 pm

=.=;

#167484 - keldon - Fri Mar 13, 2009 6:39 pm

Miked0801 wrote:
Man I forgot how ugly x86 assembler is to ARM.


Beauty is in the eye of the beholder; although that is ugly syntax - RosAsm is nice to work with.

#169651 - Karatorian - Mon Jul 27, 2009 11:51 pm

While there's some truth to the statement regarding subjective beauty, x86's uglyness goes way beyond just the syntax. I've written asm for a few platforms and the x86 ISA is ugly clear to the bare metal.