1

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?

1
  • yes, on Uno the alternative is millis()
    – Juraj
    Commented Jul 5, 2019 at 8:13

1 Answer 1

0

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:

  1. 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.

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

  3. 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.

  4. 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
2
  • Thank you so much! I have a sub-question: Timer 1 (÷64) and micros() seem equivalent in resolution, will reading Timer1 value be more accurate/reliable than using micros()?
    – Harini
    Commented Jul 9, 2019 at 3:07
  • @Harini: Reading TCNT1 will be faster than calling micros(), so you get less overhead, at the cost of a shorted rollover period. Commented Jul 9, 2019 at 7:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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