Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- inline int abs(int x)
- {
- return (x<0) ? -x : x;
- }
- Which is simple enough but contains an inline if-then-else. As the argument, x, isn’t all that likely to follow a pattern that the branch prediction unit can detect, this simple function becomes potentially costly as the jump will be mispredicted quite often.
- How can we remove the if-then-else, then? One solution is to use the right shift operator (>>) and the bitwise XOR operator (^) as following:
- inline int abs_no_branch(int x)
- {
- int m = (x >> (8 * sizeof(int)-1));
- return ((x ^ m) - m);
- }
Advertisement
Add Comment
Please, Sign In to add comment