modulo or if statement?

Let's say I've got a counter that increments on every cycle of the loop function, and I want whatever I'm doing to repeat every n loops. I can do it in at least two ways. One way uses the mod function, the other uses an if statement:

int n = 100;  // 100 just for the sake of example
int counter = 0;
void loop() {
    doStuff(counter%n);
    counter++;
}
int n = 100;  // 100 just for the sake of example
int counter = 0;
void loop() {
    if (counter == 100) {
        counter = 0;
    }
    doStuff(counter);
    counter++;
}

Which way is faster, and why?

Thanks :slight_smile:

They are not the same :wink: In the modulo example you only tell doStuff the modulo but counter is still counting beyond n. So that will cause trouble on roll over :wink: Especially because counter is signed :wink:

Think want you wanted was

int n = 100;  // 100 just for the sake of example

int counter = 0;

void loop() {
    counter %= n;

    doStuff(counter%n);

    counter++;
}

But I'm not sure which is faster, I would have to check the assembly etc. But if one is faster then it's going to by marginal. So it doesn't really matter. But I would say the modulo is more consistent, it does the same action every loop as where the if does or does not do the reset step.

Btw, I would say separating the increment and the counting limit is pretty weird. Now you end with the loop ending with counter = 100 as where you actually mean 0...

But I'm not sure which is faster

Well, I am. Limiting the magnitude of counter, and performing an if test is orders of magnitude faster than anything involving division, which modulo does.

Thanks Septillion, I see my mistake now. Whenever I've done it my way in the past I haven't had problems so I've never noticed it. I'll make sure to do it properly in future!

PaulS:

Limiting the magnitude of counter

Septillion's code now does limit the magnitude of the counter. Will this help significantly?

Also, I assumed (I guess naively) that % was a bit-manipulation level operation that in some clever way bypassed division completely. Am I to be thoroughly disappointed that it's just division then subtraction like one would do on paper?

JizzaDaMan:
Also, I assumed (I guess naively) that % was a bit-manipulation level operation that in some clever way bypassed division completely. Am I to be thoroughly disappointed that it's just division then subtraction like one would do on paper?

Be disappointed. Also it's safer to test for a greater than or equal on the upper bound, as a general rule, although it works in this case. Also more logical to group the test and increment together as was pointed out.

You didn't illustrate using n as a modulus because you hard coded it, so I'll put it back in.

int n = 100;  // modulus 100 just for the sake of example
int counter = 0;
void loop() {
    doStuff(counter);
    counter++;
    if (counter >= n)
        counter = 0;
}

Thanks :slight_smile: This is all good to know