We’re rewarding the question askers & reputations are being recalculated! Read more.

This tag is for questions about timing code execution, or external events.

Timing with millis/micros

You can, generally-speaking, time code execution by calling millis() or micros() before and after some event of interest. For example:

unsigned long startTime = millis();  // note start time
someLengthyThing();                  // do the thing we want to time
unsigned long endTime = millis();    // note end time
unsigned long elapedTime = endTime - startTime;  // calculate elapsed time

For more precise measurements use micros() (returns elapsed time in microseconds) rather than millis() (returns elapsed time in milliseconds).


Timing with digitalWrite

If calling millis/micros is not practical (you may have no way of seeing what the results are) you can also time by turning on and off a digital pin. For example:

digitalWrite (13, HIGH);  // we are about to time something - turn D13 on
someLengthyThing();       // do the thing we want to time
digitalWrite (13, LOW);   // we are done - turn D13 off

You can put an oscilloscope or logic analyser on pin 13 (or whatever pin you choose, which naturally should be set to OUTPUT mode) and then see how long the signal is high for.


Timing with writing to a port

Unfortunately, digitalWrite itself takes about 4 µs to execute, so for more accurate timing, do direct port access. For example on the Uno:

PORTB = bit (5);     // we are about to time something - turn D13 on
someLengthyThing();  // do the thing we want to time
PORTB &= ~bit (5);   // we are done - turn D13 off

These port accesses only take 250 ns which is a much lower overhead.


Also see

history | excerpt history