AND faster than integer modulo operation?

后端 未结 6 1829
自闭症患者
自闭症患者 2021-02-14 09:34

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:13

    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.

提交回复
热议问题