문제

I have a switch statement in some time-critical code. I was trying to optimize it with __builtin_expect, but it does not seem to be working. I'm wondering if anyone can tell me if I'm missing some detail, or if the compiler simply does not optimize for it. I have tried the following on my host machine:

int main() {
    volatile int v=0;
    long i = 0;

    for (i=0; i<1000000000L; i++) {
            switch(__builtin_expect(v, EXPT)) {
            case 7:
                    v=7;
                    break;
            default:
                    v=7;
                    break;
            }
    }
    return v;
}

Then I compile and run as follows:

~/code/builtinexpect> gcc bie.c -o bie -D EXPT=0 && time ./bie 

real    0m2.092s  
user    0m2.086s
sys     0m0.000s
~/code/builtinexpect> gcc bie.c -o bie -D EXPT=7 && time ./bie 

real    0m2.092s
user    0m2.086s
sys     0m0.000s

I am using GCC version 4.5.1.

도움이 되었습니까?

해결책

GCC does not support this on any architecture I'm aware of. If you have a switch statement which strongly favors a particular case, your best recourse is to do an if ... else switch ... statement. This would result in the optimization you're looking for.

다른 팁

Both case branches (and therefore all cases) do the same thing, so the compiler is free to replace the whole switch statement with v=7. Even if it doesn't (without optimization), would you expect any real difference in timing?

But more to the point, __builtin_expect evaluates as (v == EXPT), either (0) or (1), so case 7: will never be taken.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top