Learn++ Lesson 57: Measuring Execution Time in C++ Programming
Measuring execution time helps developers benchmark code and identify performance bottlenecks. This lesson uses the std::chrono library and high_resolution_clock to capture start and stop times, then converts the elapsed duration to microseconds with duration_cast.
A small example looks like this
#include <iostream>
#include <chrono>
int main() {
auto start = std::chrono::high_resolution_clock::now();
// Some code here
auto stop = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start);
std::cout << "Time taken: " << duration.count() << " microseconds";
return 0;
}
What you practice in the app
- Capturing start and stop timestamps with std::chrono::high_resolution_clock::now().
- Converting an elapsed duration to microseconds with std::chrono::duration_cast.
- Printing a measured duration for basic benchmarking.
Today's challenge
Replace the placeholder with `microseconds` to convert the duration to microseconds.