micro-optimizing loops (was Help with casts)
Chris Torek
torek at elf.ee.lbl.gov
Fri Mar 1 15:40:48 AEST 1991
>In article <10191 at dog.ee.lbl.gov> I wrote:
>>Of course, the best optimization for:
>> for (i = 1; i < 100; i++)
>> x += i;
>>is:
>> x += 4950;
In article <14522 at ganymede.inmos.co.uk> conor at inmos.co.uk (Conor O'Neill)
writes:
>No.
>Try
> { x += 4950; i = 100; }
I was assuming (perhaps unwisely) that everyone understood that the
variable `i' was `dead' after the loop. The alternative `optimizations'
under discussion were
for (i = 100; --i > 0;)
x += i;
and
for (i = 99; i; i--)
x += i;
both of which leave i==0. For these to be suitable `optimizations' for
the original (count-from-1-to-99) loop, the final value of `i' would
have to be irrelevant. (Actually, it is conceivable that the final
value of `i' might have to be exactly 0 or exactly 100; in real code,
as opposed to pedagogic examples, one should check.)
(You might also note that article <10191 at dog.ee.lbl.gov> touched lightly
on compiler transformations that changed the final value of `i' in a
count-down loop from 0 to -1. I *did* consider it....)
(Richard O'Keefe also pointed out some of the dangers in transforming
code sequences. One must always be careful of semantics. The final
value of `i' is such a semantic, and Conor O'Neill is right to be wary
of anything that alters it. In this particular example, however, the
final value should be considered irrelevant.)
--
In-Real-Life: Chris Torek, Lawrence Berkeley Lab EE div (+1 415 486 5427)
Berkeley, CA Domain: torek at ee.lbl.gov
More information about the Comp.lang.c
mailing list