coptimizationnormalization

Which one is fastest in C: fabsf(-3) or (-1)*(-3)?


Which one is fastest in C to do the L1-norm?

float x = fabsf(-3.0f);

or

float x = -1.0f * (-3.0f);

?

Both return the number x = 3


Solution

  • depends on the library used.

    Some use the x86 instruction "fabs" as in Apple's fabfs implementation:

    #define __FABSF(x) \
    ({ \
        float __value, __arg = (x); \
        asm volatile ("fabs %0,%1" : "=f" (__value): "f" (__arg)); \
        __value; \
    }) 
    

    just clear the negative bit using a bitmask, as in

    float fabsf(const float x) _MATH_REENTRANT
    {
        FS_STATIC union float_long fl;
    
        fl.f = x;
        fl.l &= 0x7fffffff;
        return fl.f;
    }
    

    or ReactOS

    {
        /* Load the value as uint */
        unsigned int u32 = *(unsigned int*)&x;
     
        /* Clear the sign bit */
        u32 &= ~(1 << 31);
     
        /* Check for NAN */
        if (u32 > 0x7F800000)
        {
            /* Set error bit */
            *(unsigned int*)&x |= 0x00400000;
            return x;
        }
     
        /* Convert back to float */
        return *(float*)&u32;
    }
    

    and no doubt some multiply by -1.

    so you'll have to write your own benchmark and tell us!