To calculate an operation execution time, I was saving the millis()
result before and after the operation to calculate the interval time. Is there an alternative on the Arduino Uno like the RDTSC found on x86 architectures?
-
yes, on Uno the alternative is millis()– Juraj ♦Commented Jul 5, 2019 at 8:13
1 Answer
There are several alternatives. The best choice for you depends on the time resolution you need and the maximum duration you may want to measure:
millis()
is good for slow things. It has a resolution of 2 ms (it increments by steps of 1 ms most of the time, but 2 ms occasionally) and can measure durations as long as 49.7 days.micros()
is the easy choice for when you want more resolution for faster things. It increments in steps of 4 µs and is limited to about 71.6 minutes.For very fast things, you can get single-cycle resolution if you configure Timer 1 to count at the full CPU speed, assuming you don't need the timer for something else. But beware the timer will roll over roughly every 4.1 milliseconds.
You could also use Timer 1 with the prescaler set at ÷8 in order to expand the measurable range to 32.8 ms, at the cost of a degraded resolution.
Here is a table summing up the available methods, sorted by resolution:
method data type resolution max. duration
--------------------------------------------------
millis() uint32_t 2 ms 49.7 days
micros() uint32_t 4 µs 71.6 min
Timer 1 (÷8) uint16_t 0.5 µs 32.8 ms
Timer 1 (÷1) uint16_t 62.5 ns 4.1 ms
-
Thank you so much! I have a sub-question:
Timer 1 (÷64)
andmicros()
seem equivalent in resolution, will readingTimer1
value be more accurate/reliable than usingmicros()
?– HariniCommented Jul 9, 2019 at 3:07 -
@Harini: Reading
TCNT1
will be faster than callingmicros()
, so you get less overhead, at the cost of a shorted rollover period. Commented Jul 9, 2019 at 7:11