guidelines on using __builtin_expect

允我心安 提交于 2019-12-10 15:42:55

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/10753456/guidelines-on-using-builtin-expect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!