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);
Multiplication is faster than division.
Division is much slower, than multiplication.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With