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.
Asked
Active
Viewed 370 times
2
-
2`micros()` is more exact. – tttapa Jan 19 '18 at 14:53
-
Here is a set of macros for benchmarking functions https://github.com/mikaelpatel/Arduino-GPIO/blob/master/src/benchmark.h. They can be used like this https://github.com/mikaelpatel/Arduino-GPIO/blob/master/examples/Benchmark/Benchmark.ino – Mikael Patel Jan 19 '18 at 15:56
3 Answers
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;
ratchet freak
- 3,277
- 1
- 11
- 12
-
2[The rollover is not an issue](https://arduino.stackexchange.com/questions/12587) as long as `foo()` executes in less than 71.5 minutes. – Edgar Bonet Jan 19 '18 at 15:11
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.
Michel Keijzers
- 12,759
- 7
- 37
- 56
-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.
4ilo
- 11
- 3
-
-
@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