Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop without comparison n times in C

Tags:

c++

c

loops

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();
}
like image 886
user2353385 Avatar asked Jan 05 '15 07:01

user2353385


2 Answers

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.

like image 125
John Zwinck Avatar answered Oct 20 '22 11:10

John Zwinck


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 counts 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
like image 40
6502 Avatar answered Oct 20 '22 13:10

6502