Search code examples
c++for-looploop-unrolling

Optimizing a program with loop unrolling


I had a question regarding loop unrolling in a for loop and how to make use in a for loop given you don't know the number of iterations until user input.

I've seen examples of loop unrolling in loops where the number of iterations are given and more instructions are being executed in one iteration. For example:

for(int i=0; i < 50; i++){ // instead of i < 200
 doSomething();
 doSomething();
 doSomething();
 doSomething();
}

My question is specific to

for(i=0; i<n; i++){
  doSomething();
}

where n is given by the user and so I don't know how to exactly make use of loop unrolling in this kind of situation.

I have wondered if I should add conditionals to this loop but that tells me it would be slowing down my program.


Solution

  • You can do it like this:

    int i = 0;
    while (i<=n-4) {
        doSomething();
        doSomething();
        doSomething();
        doSomething();
        i += 4;
    }
    while (i<n) {
        doSomething();
        i++;
    }
    

    You may want to replace the second loop with 3 ifs (as the body of the loop will be executed three times at most).

    Note, that optimizing compilers usually do this kind of transformation automatically, so you don't have to (except when they don't: Why is an integer array search loop slower in C++ than Java?).