Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Imparting expert knowledge for predicting branch statements in C# or C++

Tags:

c++

c#

I know some CPUs attempt to predict branch statements when deciding what code to pre-fetch, I was wondering if there was a way to help or hard code those branch predictions in C# (or C++). An example would be an error checking if statement which I know will return false 99.9999999% of the time, I would like to tell the CPU to always expect that branch to never happen for pre-fetching purposes.

Thanks.

like image 403
hookeslaw Avatar asked Jan 22 '11 23:01

hookeslaw


1 Answers

To the best of my knowledge there is no cross-platform solution to this problem. I would expect that C# VM would do some sort of runtime analysis to optimize for these sorts of predictions, though I don't know this for a fact.

For C/C++, there are a few platform-specific tools to help optimize this. You can usually find profile-guided optimizers for the code. I know for a fact that gcc and g++ support this, and that it can make a pretty big difference in the net program performance. gcc also supports a compiler-specific extension called __builtin_expect that lets you hardcode in your assumptions about branch prediction:

if (__builtin_expect(x == 0, 0)) { // Unlikely to occur
    /* ... */
}
like image 117
templatetypedef Avatar answered Sep 28 '22 04:09

templatetypedef