Binary Shifting
BlitzPlus Forums/BlitzPlus Programming/Binary Shifting
| ||
OK, so to multiply an integer by 256 I can simply shift the bits left by 8 which is faster than using x*256. But does anyone know a quick way to multiply by 800 or is it not possible? Maybe I should make my game 1024 pixels wide ;-) |
| ||
anyone know a quick way to multiply by 800 x = x * 800 Seriously, that's very fast. The bit shifting trick is a holdover from ancient times. Ordinary multiplication is plenty fast on modern CPU's. There is still some benefit from avoiding division, however. Whether that benefit is big enough to worry about is another question. |
| ||
My guess is that bitshifting can be handy when you're coding low-level in asm, making a fast routine like a sample-player/mixer/recorder, or anything else where each cycle truly adds to the performance and where divs/muls with powers of 2 are appropriate .. but in a Basic? I rather keep things readable, x=x*256 is more clear to me than a couple o' bitshifts.. |
| ||
You can multiply X by 800 with shifting like so: X SHL 9 + X SHL 8 + X SHL 5 Ie: X*512 + X*256 + X*32 = X*800 A quick test however for this specific case shows that floyd is correct. Running a loop approximately 65 million times, the shifting method for multiplying by 800 takes 280 milliseconds on my AMD Athalon XP 2400+, whereas multiplying by 800 the normal way takes only 200 milliseconds. Furthermore, both multiplying X by 256 and shifting X by 256 65 million times takes on average around 180 milliseconds. In other words, there is no speed benefit to shifting bits on AMD processors in Blitz, and in fact there can be a penalty to doing it if you try to be clever. I used to code on 386's, and in those days shfiting bits was really important, but I guess these days... You're not going to see any real speed boost by avoiding multiplications. But it's still not a bad idea to do bit shifting for fitting bytes together and stuff. |
| ||
Wow, quick response. I am glad modern CPUs are optimised, but I have an Intel :-o not and AMD! I'm sure it is fine though. You sure know your s**t guys! |