Built-in mod ('%') vs custom mod function: improve the performance of modulus operation

前端 未结 5 1697
逝去的感伤
逝去的感伤 2020-12-09 06:43

Recently I came to know that the mod(\'%\') operator is very slow. So I made a function which will work just like a%b. But is it faster than the mod operator?

Here\'

5条回答
  •  旧巷少年郎
    2020-12-09 07:13

    Most of the time, your micro optimized code will not beat the compiler. I also don't know where that "wisdom" comes from, that claims the built in % to be slow. It is just as fast as the machine will be able to calculate it - with all the micro optimizations the compiler can do for you.

    Also note, that performance measurements of such very small pieces of code is not an easy task. Conditionals of a loop construct or the jitter of your time measurement might dominate your results. You can find some talks on such issues by people like e.g. Andrei Alexantrescu, or Chandler Caruth on youtube. I have once written a micro benchmarking framework for a project I was working on. There is really a lot to care about, including external stuff like the OS preempting your thread, or moving it to another core.

提交回复
热议问题