If I have a loop that I know needs to be executed n times is there a way to write a while (or for) loop without a comparison each time? If not is there a way to make a macro turn:
int i = 0;
for(i = 0; i < 5; i++) {
operation();
}
into:
operation();
operation();
operation();
operation();
operation();
P.S. This is the fastest loop I've come up with so far.
int i = 5;
while(i-- >= 0) {
operation();
}
A Sufficiently Smart Compiler will do this for you. More specifically, optimizing compilers understand loop unrolling. It's a fairly basic optimization, especially in cases like your example where the number of iterations is known at compile time.
So in short: turn on compiler optimizations and don't worry about it.
The number of instructions you write in the source code is not strictly related on the number of machine instructions the compiler will generate.
Most compilers are smarter and in your second example can generate code like:
operation();
operation();
operation();
operation();
operation();
automatically because they detect that the loop will always iterate 5 times.
Also if you do a profiling-oriented optimization and a the compiler sees that a loop has tiny a body and a very high repeat count it may unroll it even for a generic number of iterations with code like:
while (count >= 5) {
operation();
operation();
operation();
operation();
operation();
count -= 5;
}
while (count > 0) {
operation();
count--;
}
This will make for large count
s about one fifth of tests compared to the naive version.
If this is worth doing or not is something that only profiling can tell.
One thing you can do if you know for sure that the code needs to be executed at least once is to write
do {
operation();
} while (--count);
instead of
while (count--) {
operation();
}
The possibility that count==0
is somewhat annoying for CPUs because requires in the code generated by most compilers an extra JMP forward:
jmp test
loop:
...operation...
test:
...do the test...
jne loop
the machine code for the do { ... } while
version instead is simply
loop:
... opertion ...
... do the test...
jne loop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With