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

后端 未结 14 798
陌清茗
陌清茗 2020-12-07 19:10

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

x=root(x²)

or

if !isPositiv         


        
14条回答
  •  醉梦人生
    2020-12-07 19:42

    The if variant will almost certainly be blindingly fast compared to the square root, since it normally translates to a conditional jump instruction at the machine code level (following the evaluation of the expression, which may be complex, but not in this case since it's a simple check for less than 0).

    Taking the square root of a number is likely to be much slower (Newton's method, for example, would use many many if statements at the machine code level).

    The likely source of confusion is the fact that if invariably lead to changing the instruction pointer in a non-sequential manner. This can slow down processors that pre-fetch instructions into a pipeline since they have to re-populate the pipeline when the address changes unexpectedly.

    However, the cost of that would be minuscule compared to performing a square root operation as opposed to a simple check-and-negate.

提交回复
热议问题