Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it more efficient to reset a counter or let it increase and use modulo

Say you need to track the number of times a method is called and print something when it has been called n times. What would be the most efficient:

  1. Use a long variable _counter and increase it each time the method is called. Each call you test for the equality "_counter % n == 0"

  2. Use an int variable _counter and increase it each time the method is called. When _counter = n, print the message and reset the variable _counter to 0.

Some would say the difference is negligible and you are probably right. I am just curious of what method is most commonly used

like image 260
Harry Avatar asked Jan 15 '23 03:01

Harry


2 Answers

In this particular case, since you need to have an if-statement ANYWAY, I would say that you should just set it to zero when it reaches the count.

However, for a case where you use the value every time, and just want to "wrap round to zero when we reach a certain value", then the case is less obvious.

If you can adjust n to be a power of 2 (2, 4, 8, 16, 32 ...), then you can use the trick of counter % n is the same as counter & (n-1) - which makes the operation REALLY quick.

If n is not a power of two, then chances are that you end up doing a real divide, which is a bad idea - divide is very expensive, compared to regular instructions, and a compare and reset is highly likely faster than the divide option.

Of course, as others have mentioned, if your counter ever reaches the MAX limit for the type, you could end up with all manner of fun and games.

Edit: And of course, if you are printing something, that probably takes 100 times longer than the divide, so it really is micro-optimization, unless n is quite large.

like image 101
Mats Petersson Avatar answered Jan 26 '23 10:01

Mats Petersson


It depends on the value of n... but I bet resetting and a simple equality check is faster. Additionally resetting the counter is safer, you will never reach the representation limit for your number. Edit: also consider readability, doing micro optimizations may obscure your code.

like image 39
Christophe Roussy Avatar answered Jan 26 '23 10:01

Christophe Roussy