Optimise nested if statements within a loop in C/C++ with GCC

I am testing various optimisations in C/C++ using the GCC compiler. I currently have a loop with multiple nested if statements, the conditions for which are computed at the beginning of the execution of the program. It looks somewhat like this:

bool conditionA = getA();
bool conditionB = getB();
bool conditionC = getC();
//Etc.

startTiming();

do {
    if(conditionA) {
        doATrueStuff();
        if(conditionB) {
            //Etc.
        } else {
            //Etc.
        }
    } else {
        doAFalseStuff();
        if(conditionB) {
            //Etc.
        } else {
            //Etc.
        }
    }
} while (testCondition());

endTiming();

Where doATrueStuff() is an inline function that does some simple numerical computation so there is no overhead in calling it.

Unfortunately, the conditions cannot be defined beforehand, they have to be computed during runtime. We can’t even reliably predict the chance of them being true or wrong. getA() might as well be rand()%2. But once computed, their value never changes.

There are two solutions I’ve thought of, one being global function pointers that are used to call the appropriate function within the loop, like this:

void (*ptrA)(void);
//Etc.

int main(int argc, char **argv) {
    //...
    if (conditionA) {
        ptrA=&aTrueFunc;
    } else {
        ptrA=&aFalseFunc;
    }
    //...
    do {
        (*ptrA)();
    } while (testCondition());
    //...
}

That way I can eliminate all branches from the loop, however then I will have the overhead of multiple function calls slowing me down.

Or I could simply have a different loop for each combination of conditions, something like this:

if(conditionA) {
    if(conditionB) {
        do {
            //Do A == true B == true stuff
        } while (testCondition());
    } else {
        do {
            //Do A == true B == false stuff
        } while (testCondition());
    }
} else {
    //Etc.
}

However that is a lot less elegant and gets impossible for one to do so efficiently once one starts having too many conditions, since for X conditions one needs to write 2^X loops.

Is there a more elegant/faster way to optimise this?

Is there even any point in this or will the compiler somehow understand that the condition doesn’t change during the loop and optimise it itself?

And out of curiosity, is there another programming language that would make writing such code easier/possible? Or would that only be possible by using assembly to change the instructions of the program once its loaded into memory?


Source: gcc

Leave a Reply