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

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

    I'm doing some retro graphics programming in C for 8088/8086 and calling abs() is time consuming so I've replaced it with:

    /* assuming 'i' is int; this WILL NOT WORK on floating point */
    if (i < 0) {
        i = ~i + 1;
    }
    

    The reason this is faster is because it essentially trades a CALL in assembly for a JNE. Calling a method changes a couple of registers, pushes several more, pushes arguments onto the stack, and can flush the prefetch queue. Plus these actions need to be reversed at the end of the function and all of this is very expensive to the CPU.

提交回复
热议问题