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

后端 未结 14 888
陌清茗
陌清茗 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:40

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

    I think the "right" answer isn't here actually. The fastest way to get the absolute number is probably to use the Intel Intrinsic. See https://software.intel.com/sites/landingpage/IntrinsicsGuide/ and look for 'vpabs' (or another intrinsic that does the job for your CPU). I'm pretty sure it'll beat all the other solutions here.

    If you don't like intrinsics (or cannot use them or ...), you might want to check if the Compiler is smart enough to figure out if a call to 'native absolute value' (std::abs in C++ or Math.Abs(x) in C#) will change automagically into the intrinsic - basically that involves looking at the disassembled (compiled) code. If you're in a JIT, be sure that JIT optimizations aren't disabled.

    If that also doesn't give you the optimized instructions, you can use the method described here: https://graphics.stanford.edu/~seander/bithacks.html#IntegerAbs .

提交回复
热议问题