Alex Rivera | Logout

AND faster than integer modulo operation?

Asked 2011-10-06T16:11:00.160
10

It is possible to re-express:

  • i % m

as:

  • i & (m-1)

where,

  • i is an unsigned integer
  • m is a power of 2

My question is: is the AND operation any faster? Don't modern CPUs support integer modulo in hardware in a single instruction? I'm interested in ARM, but don't see the modulo operation in its instruction set.

Edit
Report

1 Answer

1

If you are using a decent C compiler with optimizations enabled, it will already optimize this to whatever is faster, a technique called "strength reduction". If you're doing hand-written assembly, only sure way to test is to benchmark it. But beware, even different models of the same processor could give different results.

answered 2011-10-06T16:17:24.810

Your Answer