Reputation: 311
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.
Upvotes: 2
Views: 582
Reputation: 29932
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 if
s (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?).
Upvotes: 2
Reputation: 26066
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
If n
is given by the user and you don't know any constraints on it, you (nor your compiler) shouldn't do loop unrolling (because it could be a pessimization). If you do know something, e.g. that n
is big, it may be beneficial.
However, as @MilesBudnek points out, all these are micro-optimizations. Unless shaving off microseconds per iteration on this particular loop is critical for your application, you shouldn't approach this nor manually do anything.
Upvotes: 2