Is there a code that results in 50% branch prediction miss?

前端 未结 3 1820
醉梦人生
醉梦人生 2021-02-04 00:52

The problem:

I\'m trying to figure out how to write a code (C preffered, ASM only if there is no other solution) that would make the branch pred

3条回答
  •  攒了一身酷
    2021-02-04 01:34

    Fill an array with bytes, and write a loop that checks each byte and branches depending on the value of the byte.

    Now examine the architecture of your processor and its branch prediction very carefully. Fill the initial bytes of the array so that after examining them, the processor is in a predictable known state. From that known state, you can find out whether the next branch is predicted taken or not. Set the next byte so that the prediction is wrong. Again, find out whether the next branch is predicted taken or not, and set the next byte so that the prediction is wrong and so on.

    If you disable interrupts as well (which could change the branch prediction), you can come close to 100% mispredicted branches.

    As a simple case, on an old PowerPC processor with strong/weak prediction, after three taken branches it will always be in the state "strong taken" and one branch not taken changes it to "weak taken". If you now have a sequence of alternating not taken / taken branches, the prediction is always wrong and switches between weak not taken and weak taken.

    This will of course only work with that particular processor. Most modern processors would see that sequence as almost 100% predictable. For example, they might use two separate predictors; one for the case "last branch was taken" and one for the case "last branch was not taken". But for such a processor, a different sequence of bytes will give the same 100% misprediction rate.

提交回复
热议问题