Is multiplication faster than float division?

wodesuck picture wodesuck · Jul 26, 2013 · Viewed 26.4k times · Source

In C/C++, you can set up the following code:

double a, b, c;
...
c = (a + b) / 2;

This does the exact same thing as:

c = (a + b) * 0.5;

I'm wondering which is better to use. Is one operation fundamentally faster than the other?

Answer

Philip Couling picture Philip Couling · Jul 26, 2013

Multiplication is faster than division. At university I was taught that division takes six times that of multiplication. The actual timings are architecture dependent but in general multiplication will never be slower or even as slow as division. Always optimize your code towards using multiplication if the rounding errors allow.

So in an example this would typically be slower ...

for (int i=0; i<arraySize; i++) {
    a[i] = b[i] / x;
}

... than this ...

y=1/x;
for (int i=0; i<arraySize; i++) {
    a[i] = b[i] * y;
}

Of course with rounding errors, you'll loose (a little) precision with the second method, but unless you are repeatedly calculating x=1/x; that's unlikely to cause much issue.

Edit:

Just for reference. I've dug up a third party comparison of operation timings by searching on Google.

http://gmplib.org/~tege/x86-timing.pdf

Look at the numbers on MUL and DIV. This indicates differences of between 5 and 10 times depending on the processor.