Author: Dieter Buerssner
Date: 08:18:14 07/20/03
Go up one level in this thread
On July 20, 2003 at 08:01:50, Uri Blass wrote:
>The question is if there is a way to optimize loops without writing the same
>commands twice in the code that does the code less readable.
>
>I have in some places in movei things like
>
>while (i<n)
>{
> f(i);
> i++;
>}
>f(n);
>
>
>f is practically some C lines and not a function
>because I use some local varaibles and giving them to
>a function may make the program slower.
>
>The problem is how to avoid writing the lines of f
>twice without doing the code slower.
>
>The following option is slower because I have also
>i++ when i=n
>
>do
>{
> f(i);
> i++;
>}
>while (i<=n);
I doubt it is because of the i++. I guess it is slower because of some random
effect, that is more or less out of your control. Note that the two loops are
not identical in general (2nd one will always be executed once, while the first
one might be executed zero times). The second loop will need one branch less,
than the first one.
For loops starting at zero, sometimes it is faster to run them backwards:
instead of
for (i=0; i<n; i++)
...
for (i=n; i>0; i--)
...
But not always, this is possible. It may save a register and an instruction. I
have seen compilers to do this optimization in the for loop case, but not with
while. I would probably use do/while, which has the additional benefit, that the
source more or less documents that it will be executed at least once.
So, in some cases it could look like
do
{
...
} while (--n != 0);
If n is a compile time constant, the compiler could produce the same code from
both for loops, if not, probably not. When not really time critical (and no
other good resons), I would use the first for loop. Most probably it won't make
any significant practical difference in performance.
Regards,
Dieter
This page took 0 seconds to execute
Last modified: Thu, 15 Apr 21 08:11:13 -0700
Current Computer Chess Club Forums at Talkchess. This site by Sean Mintz.