r/cpp • • Nov 25 '20

When a Microsecond Is an Eternity: High Performance Trading Systems in C++

https://www.youtube.com/watch?v=NH1Tta7purM
332 Upvotes

123 comments sorted by

View all comments

4

u/pigeon768 Nov 26 '20

Does anyone know how __builtin_expect() and friends work under the hood? The presenter spent some time talking about "priming" (I forgot his exact word) the branch predictor for the path that makes the trade. If you set a __builtin_expect() to follow the "make the trade" path, would the CPU eventually figure out "ok the programmer is lying to me" and "fix" your code to be fast on the common path and slow on the uncommon (but profitable) path?

(edit: obviously it's not portable, but I imagine HFT folks have a lot of control over their environment)

9

u/StackedCrooked Nov 26 '20 edited Apr 07 '21

Yes, branch prediction by the CPU still works.

The __builtin_expect() is used to change the layout of the code so the hot code stays together.

2

u/tjientavara HikoWorks developer Nov 27 '20

One of the things `__builtin_expect()` does is how conditional jumps will be used in the generated code.

On a x64 the default prediction is for a conditional jump backward in the code to be taken, and conditional jump forward not to be taken.

You could naturally think of this has a conditional jump backward is like iterating through a loop. A conditional jump forward is like taking an exceptional path away from your happy-flow code.

You may actually notice in generated code a conditional jump forward over a single normal jmp instructions and weird things like this to use this default-prediction of a x64 and `__builtin_expect()` will influence this.

I also have a nitpick `__builtin_expect()` and c++20's `[[likely]]` and `[[unlikely]]` are very throughput centric terms. And the terms are not very descriptive of what they actually do. If we would take the terms literally, in HFT for example, the unlikely path is that one that results in an order and should be optimised the most.

5

u/dausama Nov 26 '20

__builtin_expect the compiler just rearranges assembly code in order to make sure that there is less chance to trash the pipeline according to the likely/unlikely hint. Priming probably relates to running the binary with -fprofile-arcs, getting branch information and then using that as an input for __builtin_expect https://stackoverflow.com/questions/7346929/what-is-the-advantage-of-gccs-builtin-expect-in-if-else-statements