I tried using millis, but I wanted to know if there is any better way to find out the exact time from when a function is called and finally when it terminates.


There is micros() which returns the number of microseconds the board has been active. But it rolls over much more frequently (a bit over an hour vs the month and a half for millis())

unsigned long preFunction = micros();
unsigned long timeElapsed = micros() - preFunction;

Beyond the answer of ratchet freak, I also suggest to (for test only), put it in a loop and divide it to get a better result, like:

unsigned long preFunction = micros();
for (int i = 0; i < 1000; i++)
unsigned long timeElapsed = (micros() - preFunction) / 1000;

The number of repeats depend on the length of foo(), make sure it will not have a value beyond an unsigned long.


The most accurate method would be to toggle a pin high right before the function, and low after.

If you than connect an oscilloscope or logic analyzer to the pin, you can measure the exact time it took for the function to execute.

  • What kind of oscilloscope? What precision do you expect to obtain? – user31481 Jan 21 '18 at 13:59
  • @LookAlterno: Any oscilloscope would do. Even a cheap pocket scope, like the DSO nano, is likely to be more accurate than micros(). – Edgar Bonet Jan 21 '18 at 15:33

Not the answer you're looking for? Browse other questions tagged or ask your own question.