Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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);

?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading