AND faster than integer modulo operation?

后端 未结 6 1186
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-14 09:19

It is possible to re-express:

  • i % m

as:

  • i & (m-1)

where,

  • i is an unsigned integer
  • m is a po
6条回答
  •  孤城傲影
    2021-02-14 10:02

    You may be interested in Embedded Live: Embedded Programmers' Guide to ARM’s Cortex-M Architecture.

    The ARM Cortex-M family has unsigned and singed division instructions, UDIV and SDIV, which take 2 to 12 cycles. There is no MOD instruction, but equivalent result is obtained by a {S,U}DIV followed by the multiply-and-subtract instruction MLS, which takes 2 cycles, for a total of 4-14 cycles.

    The AND instruction is single cycle, therefore 4-14x faster.

提交回复
热议问题