Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is divide slower than Multiply?

Ok, this might sound like a strange question but it is an interesting one. I am coding for iOS and have been told that it is always best to multiply rather than divide values as it is faster.

I know that processors these days probably make this a non issue but my curiosity has gotten the better of me and I am wondering if anyone might be able to shed some light on this for me.

SO..... My question is this -
is:

player.position = ccp(player.contentSize.width / 2, winSize.height / 2);

slower than:

player.position = ccp(player.contentSize.width * 0.5, winSize.height * 0.5);
like image 805
EcksMedia Avatar asked Sep 18 '11 05:09

EcksMedia


People also ask

Is multiplying faster than dividing?

Multiplication is faster than division.

Is division slower than multiplication Java?

Division is much slower, than multiplication.

Why is division so slow on computers?

The basic reason is that, similar to functions such as sin or sqrt, it's just mathematically more complex. IIRC, a multiplication takes about 10 cycles on an average CPU, while a division takes about 50 or more.

Is multiplying by 0.5 faster than dividing by 2?

Yes, indeed, there is a difference. A loop with a million multiplies by 0.5 took 0.11 seconds and a loop with a million divides by 2 took 1.6 seconds. So it's true for the RPG (and probably for the IBM i) that multiplying is quicker than dividing.


2 Answers

Yes, division is usually much slower than multiplication.

However, when dividing by literals (or anything that can be determined to be a constant at compile-time), the compiler will usually optimize out the division.

like image 110
Mysticial Avatar answered Oct 10 '22 17:10

Mysticial


On most processors division is slower than multiplication for the same data types. In your example your multiplication is a floating point operation, if width and height are integer types, the result may be very different and may depend on both your processor and your compiler.

However most compilers (certainly GCC) will translate a division by a constant power-of-two as in your example, to a right-shift where that would be more efficient. That would generally be faster than either a multiply or divide.

like image 21
Clifford Avatar answered Oct 10 '22 18:10

Clifford