Using ‘Mod’ on (small) Embedded Systems while Avoiding Time Penalties

The Mod/Modulo (% in C) operator is incredibly useful in many situations, it calculates the remainder from an integer division, for example 10 Mod 3 = 1 (10 Div 3 = 3, 3 * 3 = 9, 10 – 9 = 1).

Although you can happily call the % operator from your embedded C program it is important to be aware that it is typically implemented using integer division and multiplication, which is fine if your embedded system support these in hardware, if not they will be implemented in software sometimes resulting in huge time penalties (for example, on many PIC chips).

Often this won’t be a problem, but if you’re programming a real-time system these delays can be devastating! A big sting-in-the-tail from an innocent looking operator %

So what can be done:

a.) Avoid using % in your time-sensitive code, perhaps use running sums and remainders instead.

b.) Use a power-of-2 in your Mod call instead.

If the value of the right-hand operator isn’t crucial and both arguments are positive, then switching to a power of 2 will make it much easier and faster to calculate, a power-of-2 Mod can be calculated with an AND instruction.

a % b == a & (b - 1)    // if b is a power of 2 and a, b are both +ve.

Your compiler should figure out that you are using a power-of-2 and automatically carry out the optimisation, but to be safe, check the output assembly code. If it hasn’t optimised then you can replace your code with a & (b – 1)