Phil CK

Bench Signbit Check vs Float Check

Last updated on

Floats have a bit dedicated to if the value is a negative or not, I was wondering how much performance difference was checking the bit vs a function that compares against zero.

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>


#if 0
int
sign(float a) {
        return a >= 0.f ? 1 : 0;
}
#else
int
sign(float a) {
        return !((*(uint32_t*)&a >> 31) & 0xFF);
}
#endif


#define COUNT (1 << 13)


int main() {

        volatile int seed = 123;
        srand(seed);

        float data[COUNT] = {0};
        int i;

        for(i = 0; i < COUNT; ++i) {
                data[i] = ((float)(rand() % 1000) - 500.f) / 10000.f;
        }

        int result = 0;

        uint64_t start = __builtin_ia32_rdtsc();

        for(i = 0; i < COUNT; ++i) {
                result += sign(data[i]);
        }

        uint64_t end = __builtin_ia32_rdtsc();

        printf("Result: %d Time: %d\n", result, (int)(end - start));

        return 0;
}

build and go

cc signbit.c -O2 && ./a.out

Results

Signbit CheckCompare against Zero
22112871

Signbit seems to win out in all cases, but this is small enough where we can really say there is no difference. Unless you have a use case which has you doing millions of these its really not going to be worth it.