/*
* When counting in a circular fashion 0, 1, 2, 3, 0, 1 ...
* branching is more efficient than modulus (%) operation
*
*
*
*/
int counter = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
unsigned long int start;
unsigned long int finish;
// modulus operation
counter = 0;
start = millis();
for ( int i = 0 ; i < 32000 ; i++ ) {
counter = (counter + 1) % 4;
}
finish = millis();
Serial.print("modulus time: ");
Serial.println(finish - start);
// branch operation
counter = 0;
start = millis();
for ( int i = 0 ; i < 32000 ; i++ ) {
counter = counter + 1;
if (counter == 4) {
counter = 0;
}
}
finish = millis();
Serial.print("branch time: ");
Serial.println(finish - start);
}
Comments