2

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
  • 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. Commented Apr 4, 2019 at 15:26
  • 2
    try using the volatile keyword in the i variable declaration .... volatile unsigned long i = 0; Commented Apr 4, 2019 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. Commented Apr 4, 2019 at 18:28
  • Thank you all. I did it an it is working perfect. How should I mark it as answered?! :) Commented Apr 5, 2019 at 20:48

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.