An algorithm I am working on must frequently check whether some arbitrary integer value 'x' is less-than, greater-than, or equal to another arbitrary integer value 'y'. The language I am implementing it in is C.
A naive way of doing it would be to use if-then-else branching to check this, but that would not work optimally because the processor's branch predictor would mess up. I am trying to implement this comparison only using arithmetic / logical evaluations as well as bitwise operations but, honestly, my brain is stuck right now.
I will call the function f(x, y). The function will return 1, if x < y; 2, if x == y; or 3, if x > y.
One of my ideas I have had was to evaluate:
x = 3 * (x > y)
which will return 3 when x > y, and 0 otherwise. There could be an operation, which returns either 1 or 2, if x == 0 using some bitwise operators and either condition x == y or x < y, but I have not found any such combinations of operations to achieve what I need.
Finally, I am looking for any function f(x, y) which will give me my results with the least number of operations possible, be it with or without bithacks; it just needs to be fast. So if you have any other ideas I may not have considered, pointing me to another solution is also greatly appreciated.