5

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.

hookeslaw
  • 155
  • 2
  • 8
  • Why do you feel this is necessary? – Tim Lloyd Jan 22 '11 at 23:42
  • 3
    today in micro-optimization gone wild we present.. – BrokenGlass Jan 22 '11 at 23:45
  • @chibacity some times it could be very important and give some performance increase. But most brand new CPUs has quite good branch predictors with a big history cache. – Elalfer Jan 22 '11 at 23:46
  • 1
    actually the JIT compiler can gather runtime profiling info that I would think would do this sort of optimization automatically anyway, or wouldn't it? – BrokenGlass Jan 22 '11 at 23:50
  • 1
    @BrokenGlass - surely it would be jitted the first time, then left alone...? No profiling the first time... – Marc Gravell Jan 22 '11 at 23:54
  • @Marc I thought if a particular piece of code is a "hotspot" the JITer could choose to optimize later based on profiling data? If so then asymptotically it's the same - I don't know much at all about the .NET JIT compiler so I might be completely off – BrokenGlass Jan 23 '11 at 01:40

1 Answers1

5

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
    /* ... */
}
templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • This question describes how to do profile-guided optimizations with g++: http://stackoverflow.com/questions/4365980/how-to-use-profile-guided-optimizations-in-g – JaredC Jan 23 '11 at 00:38