Using branch prediction with GCC
The GNU Compiler Collection's (GCC) C compiler offers a not so commonly known builtin function for branch prediction named __builtin_expect(). It is mostly used in critical code (e.g. it's quite wide spread along some portions of the Linux Kernel source code) but can also be used to optimize your own application.
The function can be mapped as follows to some more convenient names:
#define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0)
As this is a feature specific to GCC you should make sure these macros are only expanded if GCC is used (the macro __GNUC__ is defined by GCC and compatible compilers):
#ifdef __GNUC__ # define likely(x) __builtin_expect(!!(x), 1) # define unlikely(x) __builtin_expect(!!(x), 0) #else # define likely(x) (x) # define unlikely(x) (x) #endif /* __GNUC__ */
__builtin_expect() is especially useful in cases where you're sure that the expression will almost never evaluate to true. One of these cases is the (often missed) check for a NULL pointer after calling malloc:
some_ptr = malloc(42 * sizeof(datatype_t)); if (!some_ptr) { fprintf(stderr, "Could not allocate enough memory\n"); return NULL; }
But watch out: Do not use this feature carelessly. Only use it in cases where you're very, very sure that the branch will virtually never be hit (e.g. only in low memory conditions like shown above).
More information can be found in the Kernelnewbies Wiki which also contains a comparison of assembler code generated not using branch prediction with code generated using branch prediction.

