Cooler_

trick fast

Apr 3rd, 2012
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.56 KB | None | 0 0
  1. inline int abs(int x)
  2. {
  3.     return (x<0) ? -x : x;
  4. }
  5.  
  6. 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.
  7.  
  8. 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:
  9.  
  10. inline int abs_no_branch(int x)
  11. {
  12.   int m = (x >> (8 * sizeof(int)-1));
  13.   return ((x ^ m) - m);
  14. }
Advertisement
Add Comment
Please, Sign In to add comment