Branch Predictor and Instruction Pipelining, how can I prove the existence of it?

News and research about CPU microarchitecture and software optimization
Post Reply
王家才
Posts: 1
Joined: 2023-02-10, 18:56:41

Branch Predictor and Instruction Pipelining, how can I prove the existence of it?

Post by 王家才 » 2023-02-10, 20:01:26

I was reading the source code of gstreamer and saw some "g_likely()" macros.
I know it's something related to branch predicting and I wanted to write a demo to test how much speed can benefit from this.
Then I wrote some c++ codes like following, expecting one is faster than another.

Code: Select all

#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)

val=1;
// loop 1, expected to be fast
if(likely(val))
    ...
// loop 2, predict fail, pipeline flush
if(unlikely(val))
    ...
But I tested many times on a Intel I5-8250U and saw no difference between the two statements.
After googling I reached this website. I guess it's because "static predicting" is not working, but some other predicting techniq on the processor is doing the right prediction.
Branch hint prefixes have no useful effect on PM and Core2 processors.
https://www.agner.org/optimize/microarchitecture.pdf

So, to make it short:
Is there a way I can "fool" the branch predictor and see the same code is slowed down by some well-designed dataset?


Apologize for my poor English ;)

agner
Site Admin
Posts: 75
Joined: 2019-12-27, 18:56:25
Contact:

Re: Branch Predictor and Instruction Pipelining, how can I prove the existence of it?

Post by agner » 2023-02-11, 5:29:45

The "likely" macro is a hint to the compiler, not to the CPU. The compiler may swap if-else branches to put the most likely branch first.

xiangyi
Posts: 1
Joined: 2023-04-18, 5:43:52

Re: Branch Predictor and Instruction Pipelining, how can I prove the existence of it?

Post by xiangyi » 2023-04-18, 5:46:34

https://stackoverflow.com/questions/112 ... rted-array

I recommend you to read this post and answers. The code in the post has some performance issues suffering from branch prediction failure.

agner
Site Admin
Posts: 75
Joined: 2019-12-27, 18:56:25
Contact:

Re: Branch Predictor and Instruction Pipelining, how can I prove the existence of it?

Post by agner » 2023-04-18, 6:09:05

My microarchitecture manual explains the branch prediction in different microprocessors.

Post Reply