I have a critical loop in my code with this shape :
int myloop(int a, .....){
/* some stuff */
// Critical loop
while(...){
/* Some Stuff */
if(a == 1){
// .....
}
else if(a == 2){
// .....
}
else if(a == 3){
// .....
}
else{
// ....
}
}
}
As the loop never touches the value of "a" the branch taken will never change, but as this loop is really heavy it will require to test the value of "a" many times, which is totally unnecessary. The best thing is probably to duplicate the loop, so that the "if" can be tested before the loop begins, but this would mean copying a lot of stuff common to both situations and will result in a very ugly code...
Is there any way to ask GCC/G++ to duplicate this code when it compiles it ? Or any other trick to avoid testing the value so many times ?
Thank you for your help !
Nathann
How about defining a function that does whatever happens inside the while loop and define it
inline
? Then move yourwhile
loop inside eachif
and call the function there. That will do exactly what you want.I'd suggest to pass "a" as a template parameter, ie
Like that it would be optimized away properly.
However, you won't be able to pass a variable as template parameter, so somewhere else you'd have to put that switch.
You could change the
if
block to a switch as well, which many other answers show.you could also consider moving the loop inside the conditions something like the following. This sacrifices code size for runtime efficiency.
You can use
switch
statement:How about making each a separate function, and then have a pointer to the function?