Sujet : Re: Computer architects leaving Intel...
De : tr.17687 (at) *nospam* z991.linuxsc.com (Tim Rentsch)
Groupes : comp.archDate : 07. Sep 2024, 17:33:22
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <86cylfmnjh.fsf@linuxsc.com>
References : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
User-Agent : Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux)
Bernd Linsel <
bl1-thispartdoesnotbelonghere@gmx.com> writes:
On 06.09.24 00:04, Tim Rentsch wrote:
>
If START is signed (presumably of type int), so the loop might run
zero times, but never more than INT_MAX times, then
>
for( unsigned u = START < 0 ? 0 : START + 1u; u > 0 && u--; ){
// Do something with data[i]
}
>
If START is unsigned, so in all cases the loop must run at
least once, then
>
unsigned u = START;
do {
// Do something with data[i]
} while( u > 0 && u-- );
>
(Yes I know the 'u > 0' expressions can be replaced by just 'u'.)
>
The optimizer should be smart enough to realize that if 'u > 0'
is true then the test 'u--' will also be true. The same should
hold if 'u > 0' is replaced by just 'u'.
>
(Disclaimer: code not compiled.)
>
Both yield not very elegant code:
>
https://godbolt.org/z/M4Y5PYP3v
The problem being solved is not typical. In most cases
downward-counting loops start at one past the end of the
values, not at the last value. I didn't choose the problem.
Any "inelegancy" might just as well as come from how the
optimizer was written as from the code. Clearly optimizers
do better on some patterns than others. (For that matter,
the earlier code shown may have resulted in generated code
that is just as unappealing.)
The generated code being not very elegant doesn't necessarily
imply poor performance.
In almost all cases the performance implications don't matter.
Premature optimization is the root of all evil. The first
reaction should never be to look at what code is generated.
The purpose of the example (besides fixing a bug in the original,
which was removed) is, one, to illustrate an idea, and two, to
show an alternate example pattern that may help in unrelated
cases. It helps to be familiar with different approaches to
common situations. For this particular problem, probably it's
better to revise code outside the loop so the loop would be
done differently. The point here is not this code specifically
but a pattern and a principle that might be applicable in a
range of coding circumstances.