How expensive is it to convert between int and double?

后端 未结 2 978
迷失自我
迷失自我 2020-12-29 05:23

I often see code that converts ints to doubles to ints to doubles and back once again (sometimes for good reasons, sometimes not), and it just occurred to me that this seems

2条回答
  •  再見小時候
    2020-12-29 06:14

    Of course this kind of question depends on the exact hardware and even on the mode.

    On x86 my i7 when used in 32-bit mode with default options (gcc -m32 -O3) the conversion from int to double is quite fast, the opposite instead is much slower because the C standard mandates an absurd rule (truncation of decimals).

    This way of rounding is bad both for math and for hardware and requires the FPU to switch to this special rounding mode, perform the truncation, and switch back to a sane way of rounding.

    If you need speed doing the float->int conversion using the simple fistp instruction is faster and also much better for computation results, but requires some inline assembly.

    inline int my_int(double x)
    {
      int r;
      asm ("fldl %1\n"
           "fistpl %0\n"
           :"=m"(r)
           :"m"(x));
      return r;
    }
    

    is more than 6 times faster than naive x = (int)y; conversion (and doesn't have a bias toward 0).

    The very same processor, when used in 64-bit mode however has no speed problems and using the fistp code actually makes the code run somewhat slower.

    Apparently the hardware guys gave up and implemented the bad rounding algorithm directly in hardware (so badly rounding code can now run fast).

提交回复
热议问题