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 −

Example

void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   long int t1 = millis();
   task_whose_time_is_to_be_measured();
   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().

Updated on: 26-Oct-2023

22K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements