How can this sketch run so fast?

Hi all, can someone please explain this to me?

This sketch:

void setup() {
  Serial.begin(115200);
}

void loop() {
  unsigned long start, count;

  count = 0;
  start = micros();
  for (int c=0; c<10000; c++) {
    for (int d=0; d<10000; d++) {
      count++;
    }
  }

  Serial.print("Repetitions: ");
  Serial.println(count);
  Serial.print("Time in micros: ");
  Serial.println(micros() - start);

  delay(1000);
}

Output:

Repetitions: 100000000
Time in micros: 788
Repetitions: 100000000
Time in micros: 796
Repetitions: 100000000
Time in micros: 780
Repetitions: 100000000
Time in micros: 796

So the nested for-loops are repeating the “count++” operation 100,000,000 times. In less than 1ms? This is running on a 16MHz Nano 3…

Am I being really thick or is the compiler being really clever?

Make count volatile so it is not optimized away. The compiler can see it has no side effects and is optimized (can be computed at compile time), rendering the loops unnecessary.

You were right. Making count volatile and reducing the reps down to 10,000:

Repetitions: 10000
Time in micros: 15700
Repetitions: 10000
Time in micros: 15708
Repetitions: 10000
Time in micros: 15700

So the compiler is really, really clever! It worked out that the end result would be (in the first example) 100,000,000 and skipped the actual loops!