What is different about C++ math.h abs() compared to my abs()
- by moka
I am currently writing some glsl like vector math classes in c++, and I just implemented an abs() function like this:
    template<class T>
    static inline T abs(T _a)
    {
        return _a < 0 ? -_a : _a;
    }
I compared its speed to the default c++ abs from math.h like this:
clock_t begin = clock();
    for(int i=0; i<10000000; ++i)
    {
        float a = abs(-1.25);
    };
    clock_t end = clock();
    unsigned long time1 = (unsigned long)((float)(end-begin) / ((float)CLOCKS_PER_SEC/1000.0));
    begin = clock();
    for(int i=0; i<10000000; ++i)
    {
        float a  = myMath::abs(-1.25);
    };
    end = clock();
    unsigned long time2 = (unsigned long)((float)(end-begin) / ((float)CLOCKS_PER_SEC/1000.0));
    std::cout<<time1<<std::endl;
    std::cout<<time2<<std::endl;
Now the default abs takes about 25ms while mine takes 60. I guess there is some low level optimisation going on. Does anybody know how math.h abs works internally? The performance difference is nothing dramatic, but I am just curious!