Alternative to using % operator and / Operator in C++

kiki picture kiki · Nov 15, 2011 · Viewed 10.3k times · Source

It is told that modulo operator "%" and divide operator "/" are very inefficient in embedded C++.

How can I alternatively achieve the following expression:

a = b % c;

I understand that this can be achieved using the following logic:

a = b - c;
while (a >= c) {
  a = a - c;
}

But my question is, is this code involving while loops efficient enough, compared to % operator?

Thanks, Kirti

Answer

Basile Starynkevitch picture Basile Starynkevitch · Nov 15, 2011

Division and modulus are indeed costly hardware operations, whatever you do (this is more related to hardware architecture than to languages or compilers), perhaps ten times slower than addition.

However, on current laptops or servers, and on high-end microcontrollers, cache misses are often much slower than divisions!

The GCC compiler is often able to optimize them, when the divisor is a constant.

Your naive loop is usually much more slower than using the hardware division instruction (or the library routine doing it, if not provided by hardware). I believe you are wrong in avoiding the division & replacing it with your loop.

You might tune your algorithms -e.g. by having power of twos- but I don't recommend using your code. Remember that premature optimization is evil so first try to get your program correct, then profile it to find the trouble spots.