Calculate time of operation in Arduino

Often, you need to measure the time your microcontroller takes to perform a particular task. You can use the millis() function of Arduino to measure the time. This function returns the number of milliseconds passed since your board started running the current program. Therefore, to calculate the time taken by an operation, you can call millis() before and after your operation, and take the difference of the two values.

An example implementation is given below −


void setup() {
   // put your setup code here, to run once:
   long int t1 = millis();
   long int t2 = millis();
   Serial.print("Time taken by the task: "); Serial.print(t2-t1); Serial.println(" milliseconds");
void loop() {
   // put your main code here, to run repeatedly:

As you can see, this will give the execution time of the task in milliseconds. But what if you want the execution time to be in microseconds? You guessed it! You can use micros() instead of millis().