[comp.lang.c] What looks efficient may not be

ray@saturn.ucsc.edu (Ray Swartz) (05/27/89)

I recently was surprised to discover that 

     while (i < 500000)
	 ++i;


ran much faster than

     while (i < 500000))
	  i++;


The test ran on a 68020 based machine.  This test was run without using
the optimizer.  Here is yet another example that shows that optimizing
from a higher level language may backfire.
Incidentally, I realize the loops don't do anything, I was testing some 
alternatives ways of doing timing loops.

poser@csli.Stanford.EDU (Bill Poser) (05/29/89)

In article <7703@saturn.ucsc.edu>, ray@saturn.ucsc.edu (Ray Swartz) writes:
> I recently was surprised to discover that 
> 
>      while (i < 500000)
> 	 ++i;
> 
> ran much faster than
> 
>      while (i < 500000))
> 	  i++;
> 
> The test ran on a 68020 based machine.  This test was run without using
> the optimizer.  Here is yet another example that shows that optimizing
> from a higher level language may backfire.

I don't see what this shows about optimizing from a higher level language.
Shouldn't we expect a compiler that doesn't generate identical code for these
two loops to generate faster code for the ++i case because the question of
saving a copy of the unincremented variable does not arise? That is,
presumably what is happening is that the compiler is generating 
(pseudo-assembler) something like:

	addl2 $1 i

for the pre-increment but

	movl i foo		# save unincremented value
	addl2 $1 i
	
for the post-increment.

Of course, a smart compiler will recognize that in these examples
the value of i is never used and will not bother with the save.

I tried these examples on an HP 9000/350 (68020-based) running HPUX 5.22
and a VAX 11/750 running 4.2BSD and got identical assembler output for the
pre- and post-increments (without the optimizer), so it looks like
the compiler on Ray Swartz' machine isn't very smart.

cowan@marob.masa.com (John Cowan) (06/01/89)

In article <9146@csli.Stanford.EDU> poser@csli.Stanford.EDU (Bill Poser) writes:
[in reference to two loops, one of which pre-increments a variable,
and the other post-increments a variable, and nothing else]

>Of course, a smart compiler will recognize that in these examples
>the value of i is never used and will not bother with the save.
>

A >really< smart compiler would recognize that the loops don't do anything
at all, and kill them both!
-- 
John Cowan <cowan@marob.masa.com> or <cowan@magpie.masa.com>
UUCP mailers:  ...!uunet!hombre!{marob,magpie}!cowan
Fidonet (last resort): 1:107/711
Aiya elenion ancalima!