4

What should I wrap with the gcc's __builtin_expected macros within an if with multiple and nested tests? I have this code:

if((x<RADIUS && (forward?v<0:v>0)) || (x+RADIUS>dimensions[d] && (forward?v>0:v<0)))

I have (ridiculously) wrapped everything I could:

#define likely(x)       __builtin_expect((x),1)
#define unlikely(x)     __builtin_expect((x),0)
if(unlikely(unlikely(unlikely(x<RADIUS) && likely(likely(forward)?likely(v<0):likely(v>0))) || unlikely(unlikely(x+RADIUS>dimensions[d]) && likely(likely(forward)?likely(v>0):likely(v<0)))))

I hope it's just an overkill, because it's pretty much unreadable.

Lorenzo Pistone
  • 5,028
  • 3
  • 34
  • 65
  • 4
    Where are you planning to run this code? In practice on modern x86 CPUs the branch predictors are much better than static hints anyhow, i.e. if you run the code often enough and there's a simple pattern they'll easily pick it up. If you *don't* run the code often enough, why do you think a few cycles would matter much? Now if one of your target platforms is ARM, it probably is not such a bad idea. – Voo May 25 '12 at 16:39

1 Answers1

4

I don't think there's a wrong answer here. The compiler will use your hints to decide which case to make the "else" case of every comparison; that's not just the C code else, but within the ands and ors of the logic also, and the more information the better.

For the sake of readable code, I'd suggest keeping it to the big stuff: once for each if statement, but that's not really based on any hard evidence.

Have you considered using -fprofile-generate, run the code with typical data, and then rebuild with -fprofile-use? That way the compiler can build it's own picture for all these cases. This is more portable (no compiler-specific annotations), more readable, and more future proof.

ams
  • 24,923
  • 4
  • 54
  • 75