How to Measure Elapsed Time in C++
Elapsed time in C++ can be calculated by taking two of the timestamps, that is, at the beginning and end of the execution of the program. The elapsed time is calculated by obtaining the difference between them, by subtracting the start time from the end time and returning the elapsed time. The <chrono> is a header file in C++ that allows to perform multiple functions related to time, including the calculation of elapsed time. This is a program written to calculate its elapsed time:
#include <thread>
#include <chrono>
std::chrono::milliseconds MAX_DURATION(80);
int main() {
std::chrono::time_point start = std::chrono::steady_clock::now();
std::this_thread::sleep_for(std::chrono::milliseconds(100)); // simulate execution of something to measure
std::chrono::time_point stop = std::chrono::steady_clock::now();
std::chrono::duration elapsed = stop - start;
std::cout << "Elapsed: " << elapsed.count() << " ms" < MAX_DURATION) {
std::cout << "Longer than the Maximum Duration!" << std::endl;
}
}
In this program, <chrono> header file is specifically included to deal with the time-related operations. The maximum time duration is set to be 80 milliseconds for the program. The standard measuring time is set to be milliseconds to obtain the accurate elapsed time because most of the parts of programs take milliseconds to execute. The start time is taken as a reference and then the process is set to execute. After complete execution, an end time is measured too. Then start time is subtracted from the start time to calculate elapsed time. If the statement is used to check at the end of the code if the elapsed time is greater than the maximum time.
The elapsed time for the code is calculated as 97.8577 milliseconds. As it is greater than the maximum time an argument is returned for it.
Conclusion
Elapsed time refers to the time period that is passed between the start and end time of the event. It is a good practice to measure the elapsed time of a program to judge the efficiency of it. Elapsed time in C++ can be calculated by finding the difference between the starting and the ending time of the executed code.