Help with casts

Paul Falstad pfalstad at phoenix.Princeton.EDU
Sun Feb 24 06:25:29 AEST 1991


garry at ceco.ceco.com (Garry Garrett) wrote:
>In article <339 at smds.UUCP>, rh at smds.UUCP (Richard Harter) writes:
>> This is better done as 
>> 
>>       for (i=100;--i>=0;)
>>          x += i;

>  I must disagree with you.  For starters, consider the situation where
>i == 0.  Your loop adds 0 to x.

What he meant was, for(i=0; i <= 100; i++) is not equivalent to
for(i=100; i; i--) for a non-trivial loop body.  Your version executes
the loop 1 less time than his.  If you really want to optimize this
code, you could just say x = 5050.

>pointed out, performing "--i>=0" would take more time than "i"  The reason is
>that both i and 0 must be loaded into registers, compared, and a branch 
>instruction executed for your version.  My version loads i into a register
>and performs a branch.  2 steps vs. your 4 steps.  Is I pointed out making i

Even without optimization turned on, my compiler was smart enough not to
load 0 into a register.  It took 2 instructions to do i>=0.

>  Bear in mind that C is one of the hardest languages in the world to
>optimize.  For instance, in pascal the index of a for loop cannot be referenced
>outside of that loop, thus the code can be optimized by making that index a
>register variable.  In C, you can reference i later in the code, so the compiler
>cannot make that assumption for you.  You must explicitly ask the compiler
>to make a varible into a register variable by declairing it as such.  There

What?  What difference does it make if i is referenced later?  The only
reason it might not be possible to make i a register variable is that i
might need to be addressable.  I don't see what next-use information has
to do with it.  With optimization turned on, both compilers I tried put
i and x in registers.

>  If your computer's CPU's ALU has an option to compare a register to 0,
>and you assembler has a command to use that option, and your C compiler knows
>that that option exists, and your C compiler is smart enough to optimize --i>=0
>to make use of that assemby instruction, then your method would compile to:
>load i into a register, compare it to 0, conditional branch.  3 instructions to
>my 2.  Sorry, but my code is still faster.

I don't think there will be a large difference.  In fact, the Sun SPARC
compiler took 5 instructions to do your version, 3 for his.  Don't think
you're saving any time by writing "i" instead of "i != 0"; some
compilers automatically convert "i" to "i != 0" internally.

--
  Paul Falstad, pfalstad at phoenix.princeton.edu PLink:HYPNOS GEnie:P.FALSTAD
  I think there should be more race prejudice.  <slap> LESS race prejudice.
     Princeton University apologizes for the content of this article.



More information about the Comp.lang.c mailing list