Portable branch prediction hints

Viewed 12376

Is there any portable way of doing branch prediction hints? Consider the following example:

  if (unlikely_condition) {
    /* ..A.. */
  } else {
    /* ..B.. */
  }

Is this any different than doing:

  if (!unlikely_condition) {
    /* ..B.. */
  } else {
    /* ..A.. */
  }

Or is the only way to use compiler specific hints? (e.g. __builtin_expect on GCC)

Will compilers treat the if conditions any differently based on the ordering of the conditions?

6 Answers

C++20 offers likely and unlikely attributes

Allow the compiler to optimize for the case where paths of execution including that statement are more or less likely than any alternative path of execution that does not include such a statement

Related