Tech Off Thread
7 postsForum Read Only
This forum has been made read only by the site admins. No new threads or comments can be added.
what is more expensive?

a simple comparison of two integers
if (x > y) {
}
or
a multiplication
x *= 1; 
Generally speaking multiplication is more expensive, however the compiler will optimize this particular multiplication (by a constant 1) to use the "neg" instruction, which I think is about the same as a "jle" or similar.

Depends on the language/compiler/chip. Mults are pretty expensive though, generally speaking.

DoomBringer wrote:Depends on the language/compiler/chip. Mults are pretty expensive though, generally speaking.
Agreed.
But I remember that since the age of C++ for DOS, the compiler will optimize "multiplication with constant" to "a sequence of shift + increment instructions" that I believe is still working in the new C++ releases, and possibly other compilers too. So it could be not that expensive anyway.

cheong wrote:
DoomBringer wrote: Depends on the language/compiler/chip. Mults are pretty expensive though, generally speaking.
Agreed.
But I remember that since the age of C++ for DOS, the compiler will optimize "multiplication with constant" to "a sequence of shift + increment instructions" that I believe is still working in the new C++ releases, and possibly other compilers too. So it could be not that expensive anyway.
I took CPU architecture my last semester, and the overall algorithm for mults was pretty intense. Its implemented in hardware, yes, but requires a few cycles to get done. Throw in overflow checking or whatever (two 16 bit numbers can grow into 32 bits...) and other stuff, the mult is pretty expensive. Division is worse yet.
Of course, modern day optimization in a compiler and really honking fast CPUs are the norm. Even on a RIM BlackBerry, I have 1632 MB of memory and a 400mhz ARM chip, which is surprisingly capable. I've done some pretty amazing work with getting my code ultratrim but even without that things were pretty good.
Multiplication by a constant will probably get optimized pretty heavily, especially a negation like * 1. 
Optimization of multiplication is a fascinating field.
Multiplication by certain numbers is very fast:
x * 0 == 0
x * 1 == x
x * 1 == ~x + 1
Multiplication by other numbers is quite fast:
x * 2 == x << 1
x * 4 == x << 2
x * 16 == x << 4
...
In general, the unavoidable cost of a multiplication is proportional to the number of "on" bits in the multiplicand with the fewer number of "on" bits. 
If you have fast ln() and exp() functions, you can also use the following for floatingpoint numbers:
float MultiplyInRoundaboutWay(float x, float y) {
return exp(ln(x) + ln(y));
}
Conversation locked
This conversation has been locked by the site admins. No new comments can be made.