2

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.

2
2

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();
foo();
unsigned long timeElapsed = micros() - preFunction;
1
0

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++)
{
  foo();
}
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.

-1

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.

2
  • 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.