www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - "likely" keyword for D?

reply %u <wfunction hotmail.com> writes:
I just thought of a (crazy) idea:

Should D implement a "likely" keyword for if statements?
Something like:

if likely (x == 2)
{
    //do something
}

This would allow the compiler to generate branch prediction code for
the program, allowing the programmer to prevent branch predictions.

It's a crazy (and new?) idea... any thoughts?
Mar 22 2011
next sibling parent Andrej Mitrovic <andrej.mitrovich gmail.com> writes:
That will be a special feature available only in DMD Quantum Edition=AE.
Mar 22 2011
prev sibling parent reply Peter Alexander <peter.alexander.au gmail.com> writes:
On 23/03/11 4:59 AM, %u wrote:
 I just thought of a (crazy) idea:

 Should D implement a "likely" keyword for if statements?
 Something like:

 if likely (x == 2)
 {
      //do something
 }

 This would allow the compiler to generate branch prediction code for
 the program, allowing the programmer to prevent branch predictions.

 It's a crazy (and new?) idea... any thoughts?

Would be better as a compiler intrinsic instead of introducing a new keyword. GCC uses __builtin_expect: long __builtin_expect (long exp, long c) if ( __builtin_expect(ptr != 0, 1) ) { // expect non-null } In this day and age it's rarely useful. Modern processors have branch prediction tables built in to them, so while you may be able to avoid the first branch misprediction, the CPU will probably predict the rest of them correctly anyway.
Mar 23 2011
parent Don <nospam nospam.com> writes:
Peter Alexander wrote:
 On 23/03/11 4:59 AM, %u wrote:
 I just thought of a (crazy) idea:

 Should D implement a "likely" keyword for if statements?
 Something like:

 if likely (x == 2)
 {
      //do something
 }

 This would allow the compiler to generate branch prediction code for
 the program, allowing the programmer to prevent branch predictions.

 It's a crazy (and new?) idea... any thoughts?

Would be better as a compiler intrinsic instead of introducing a new keyword. GCC uses __builtin_expect: long __builtin_expect (long exp, long c) if ( __builtin_expect(ptr != 0, 1) ) { // expect non-null } In this day and age it's rarely useful. Modern processors have branch prediction tables built in to them, so while you may be able to avoid the first branch misprediction, the CPU will probably predict the rest of them correctly anyway.

For a processor like x86, even in the rare cases where it could make a difference, the code to take advantage of it isn't consistent between processors. Eg code that will benefit Pentium4 will slow down other processors. AFAIK one of the few processors that strongly benefits from knowledge of branch prediction probabilities is the Itanium; but IMHO this is better dealt with by profile-guided optimisation than by annotating the source code.
Mar 23 2011