Hello,
for the game I'm currently developing, I use the % (modulo) operator on a per-pixel basis (on some parts), which terribly lowers the framerate. Is there any way to perform a modulo operation faster or should I try to find a way to lower the usage?
Thanks
Bad, bad, bad, bad, bad! Modulos is division and division is SLOW.
If you can't lower the usage then try to only modulos by a number that is 2^n (that is 2 to the power of n, not XOR). Then you can create a bitmask by setting the right-most n bits to 1, and then & (bitwise AND) to do fast modulos.
Along the same lines, you can quickly divide by 2^n by shifting right n bits.
Dan East
Here's an example. Say you want to modulos by 64. Precalc the bitmask which is 64-1 (2^n=64, n=6, which is a mask of 00111111 or 63). Once you have your mask all you have to do is AND some integer by it:
- Code:
int divisor=64;
int mask=divisor-1;
int i=1234;
int result1 = i & mask;
int result2 = i % divisor;
//result1 and result2 are the same ( 18 )
Dan East
Hey, thanks, very cool idea. I'm already using bitshifts for most multiplications and divisions (which works fine, since my tiles are 32*16 pixels), but using bitmasks for modulo ist really neat.
Thanks!!