Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to aid branch prediction?

Can you intentionally write code in a specific way so that the branch predictor will choose the option that will be the case most of the times. For example error checks whether a resource was loaded. If this is possible how can you use this to your advantage?

like image 424
Morgangrauen Avatar asked Jan 05 '23 19:01

Morgangrauen


2 Answers

If you are using GCC you can use the macros `likely()/unlikely()':

likely()/unlikely() macros in the Linux kernel - how do they work? What's their benefit?

like image 184
Sasha Pachev Avatar answered Jan 08 '23 08:01

Sasha Pachev


Theoretically, yes. Effectively speaking NO. You won't really get any benefit, try it out yourself.

With the way modern hardware works your CPU will still grind out all of the branches no matter what you do. But it doesn't really matter because they will do it concurrently.

To attempt to do it yourself you would need to use assembly language. Compiler hints like shown above will not do much.

like image 37
Yudrist Avatar answered Jan 08 '23 08:01

Yudrist