What has a better performance: multiplication or division?

后端 未结 4 1862
天涯浪人
天涯浪人 2020-12-18 07:00

Which version is faster ? x * 0.5 or x / 2

Ive had a course at the university called computer systems some time ago. From back then i remember that mult

4条回答
  •  粉色の甜心
    2020-12-18 07:44

    Division by a compile-time constant that's a power of 2 is quite fast (comparable to multiplication by a compile-time constant) for both integers and floats (it's basically convertible into a bit shift).

    For floats even dynamic division by powers of two is much faster than regular (dynamic or static division) as it basically turns into a subtraction on its exponent.

    In all other cases, division appears to be several times slower than multiplication.

    For dynamic divisor the slowndown factor at my Intel(R) Core(TM) i5 CPU M 430 @ 2.27GHz appears to be about 8, for static ones about 2.

    The results are from a little benchmark of mine, which I made because I was somewhat curious about this (notice the aberrations at powers of two) :

    • ulong -- 64 bit unsigned
    • 1 in the label means dynamic argument
    • 0 in the lable means statically known argument

    The results were generated from the following bash template:

    #include 
    #include 
    typedef unsigned long ulong;
    int main(int argc, char** argv){
        $TYPE arg = atoi(argv[1]);
        $TYPE i = 0, res = 0;
        for (i=0;i< $IT;i++)
            res+=i $OP $ARG;
        printf($FMT, res);
        return 0;
    }
    

    with the $-variables assigned and the resulting program compiled with -O3 and run (dynamic values came from the command line as it's obvious from the C code).

提交回复
热议问题