CodingHowTo

Micro Timer: Measure Execution Time with std::chrono

Micro Timer: Measure Execution Time with std::chrono

Content


#include <iostream>
#include <chrono>

int main() {
    auto start = std::chrono::high_resolution_clock::now();

    // Your code here
    for (int i = 0; i < 1000000; ++i) {
        // Some operation
    }

    auto end = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::micro>(end - start);

    std::cout << "Execution time: " << duration.count() << " microseconds" << std::endl;

    return 0;
}

Here's a breakdown of the code:

  • We include the necessary headers for input/output and time measurement.
  • We use std::chrono::high_resolution_clock::now() to get the current time before and after the block of code we want to measure.
  • The difference between these two times is calculated using std::chrono::duration_cast<std::micro>, which gives us the duration in microseconds.
  • Finally, we print the execution time to the console.

Conclusion

Measuring execution time is a fundamental technique for understanding and optimizing code performance. Using C++17's std::chrono, you can achieve precise microsecond-level timing with just a few lines of code. This method is not only efficient but also portable across different platforms, making it an excellent choice for performance analysis.