Search code examples
algorithmperformancetheoryabsolute-value

Which is the fastest way to get the absolute value of a number


Which is the fastest way to implement an operation that returns the absolute value of a number?

x=root(x²)

or

if !isPositive(x):
    x=x*(-1)

Actually this question can be translated as, how fast is an if (and why please).

My college programing professors always told me to avoid ifs for they are extremely slow, but I always forgot to ask how slow and why. Does anybody here know?


Solution

  • Conditionals are slower than plain arithmetic operations, but much, much faster than something as silly as calculating the square root.

    Rules of thumb from my assembly days:

    • Integer or bitwise op: 1 cycle
    • Floating-point add/sub/mul: 4 cycles
    • Floating-point div: ~30 cycles
    • Floating-point exponentiation: ~200 cycles
    • Floating-point sqrt: ~60 cycles depending on implementation
    • Conditional branch: avg. 10 cycles, better if well-predicted, much worse if mispredicted