1

I am using ESP32 Pico Kit with Arduino Ide. I want to measure operation cycle for a few commands.

The code is so simple as below:

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

void loop() {
  unsigned long count = 10000;
  unsigned long i = 0;
  unsigned long _start;
  unsigned long _end;
  _start = ESP.getCycleCount();
  while(i < count)
  {
    i++;
  }
  _end = ESP.getCycleCount();
  Serial.println(_end - _start);
}

When I run the code, the result is 13.

Then, I changed the counter variable to different values and ran it again (values: 10, 100, 1000, 10000, ...).

The result is always 13!

Why the execution cycle does not change and it seems that the code is compiled as just one loop and the loop count is not important?

Am I missing something?

  • 4
    I think the compiler sees what you are doing, and just replace the while loop with i=count. The compiler tries to optimize your code. – Gerben Apr 4 at 15:26
  • 2
    try using the volatile keyword in the i variable declaration .... volatile unsigned long i = 0; – jsotola Apr 4 at 15:39
  • 3
    Not only does the compiler remove the loop, it also removed the variables i and count altogether. Or at least any decent optimizing compiler would do so. – Edgar Bonet Apr 4 at 18:28
  • Thank you all. I did it an it is working perfect. How should I mark it as answered?! :) – Amir Pournasserian Apr 5 at 20:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.