0

I wrote the following scope-based timer to help me profile my code and improve its efficency, but in testing I found that it reports durations far shorter than it should:

class CodeTimer {
 public:
  CodeTimer(const String& name) : _name(name) {
    Serial.println("Begin execution of \"" + _name + "\".");
    _begin = micros();
  }

  ~CodeTimer() {
    unsigned long duration = micros() - _begin;
    Serial.println("\"" + _name + "\" execution took " + duration + "µs.");
  }

 private:
  unsigned long _begin;
  String _name;
};

For example, I'd use it like so in my sketch:

void setup() {}

void loop() {
  CodeTimer("void loop()");
  int begin = millis();

  delay(100); // Simulation of work that takes 100ms.
  Serial.println(millis() - begin);
}

Then, when I go to run the above sketch on my Blue Pill board (STM32F103C8), I get something like this printed to the terminal:

Begin execution of "void loop()".
"void loop()" execution took 4µs.
100
Begin execution of "void loop()".
"void loop()" execution took 3µs.
101
Begin execution of "void loop()".
"void loop()" execution took 4µs.
100

Something is very wrong with when the destructor to CodeTimer is being called, and I'm not exactly sure what it is.

  • the code is optimized by the compiler. It executes the prints and ready. there is no reason to hold the object on stack longer – Juraj Mar 2 at 6:24
  • @Juraj Interesting... Is there any way I can prevent it from doing this? – ifconfig Mar 2 at 7:03
  • Access the instance after the delay. – the busybee Mar 2 at 7:34
  • @Juraj This makes sense, thank you. However, I'd still be interested in knowing if there's some sort of compiler flag or keyword I can use to prevent this behavior. – ifconfig Mar 2 at 7:34
  • 1
    :-) the coders on Stack Overflow have better eyes (or experience). the variable name is missing so there is no variable to live until the end of the scope stackoverflow.com/questions/60496359/… – Juraj Mar 3 at 7:15

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.