Hi all,
For a timing-critical project I am trying to understand how long it takes Arduino to carry out certain functions. One of the tests that I did involved a counter within a simple conditional statement to see how often that statement can be carried out in a second. I noticed that there is a large difference between using the 'while'-statement and the 'if'-statement. The first one seems to carry out twice as fast as the second.
The 'while'-code:
unsigned long timer = 0;
unsigned long counter = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
while (timer < (millis() - 1000)){
counter++;
}
Serial.print("Speed of calculation: ");
Serial.print(counter);
Serial.println(" Hz");
}
And the almost identical 'if'-code:
unsigned long timer = 0;
unsigned long counter = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
if (timer < (millis() - 1000)){
counter++;
}
else {
Serial.print("Speed of calculation: ");
Serial.print(counter);
Serial.println(" Hz");
}
}
Results:
While-code: 269669 Hz;
If-code: 134835 Hz
Difference 134835 / 269669 = 0.5
Any idea why the if-statement takes twice as long?