Search query #92385295
April 14, 2009
It was nice to read someone around the Internet is googling for “optimize code int a = b * 4″.
Of course, most people would think that it shouldn’t be optimized at all, and you’re sort of right, most compilers will optimize this simple piece of code.
But should you want to do it by yourself, there are two nice ways of doing this.
Before I start, I truly hope no compiler will translate this to a MUL opcode, it will eat your cpu-time like pacman when you have the code inside a loop.
The number 4 is awesome, why? Because it’s a multiple of 2. The extra options you instantly get for both division and multiplication when using a multiple of 2 are the opcodes SHR and SHL. Those commands just simply shift all the bits inside a register to the left or to the right. This effectively means that with a simple and fast opcode you can divide by using SHR (div 2 per bit) and multiply by using SHL (mul 2 per bit).
The problem of SHL and SHR is that not every programming language supports direct translation to these opcodes. In C/C++ however you can use “a = b << 2;” for the equivalent of ”a = b * 4;”, and in Delphi you can use “a := b shl 2;” (I think).
Some other languages do have a bitwise shift function, but they use the rotation shift opcodes (ROL and ROR), which prepends or appends any bits that might’ve fallen off of the other side of your limits. These aren’t the functions you’ll be looking for when multiplying (and dare I say they rarely have any use in the real world).
A slight hickup about SHL and SHL is that some very very old CPU’s didn’t support shifting by more than 1 bit. But you’ll have trouble finding them old pre-486 cpu’s that didn’t.
So yeah, multiplying by 4 is fun. On the other hand, if you have to use odd numbers like 3 and 5, the only option you could consider is using addition instead of multiplication. I doubt however that you’ll get much speed out of that nowadays, unless you’re recursively/iteratively multiplying previous results like in this post.
So there it is, needing to multiple or divide by 2 – use bitwise opcodes.
Entry Filed under: optimization. .
Trackback this post | Subscribe to the comments via RSS Feed