Lorenzo Pistone
Lorenzo Pistone

Reputation: 5188

guidelines on using __builtin_expect

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.

Upvotes: 4

Views: 1219

Answers (1)

ams
ams

Reputation: 25599

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.

Upvotes: 4

Related Questions