Odds and Ends: 10 Useful Techniques

Measuring execution time with <chrono>

How can I measure the execution time of a function using the <chrono> library?

Abstract art representing computer programming

You can use the <chrono> library to measure the execution time of a function by following these steps:

  1. Get the current time point before executing the function using std::chrono::high_resolution_clock::now().
  2. Execute the function you want to measure.
  3. Get the current time point after the function execution.
  4. Calculate the duration between the start and end time points using std::chrono::duration_cast.

Here's an example:

#include <chrono>
#include <iostream>

void someFunction() {
  // Function code goes here
}

int main() {
  using namespace std::chrono;
  auto start = high_resolution_clock::now();  
  someFunction();
  auto end = high_resolution_clock::now();  

  auto duration = duration_cast<microseconds>(
    end - start);  

  std::cout << "Execution time: "
    << duration.count() << " microseconds\n";
}
Execution time: 3 microseconds

The std::chrono::high_resolution_clock provides the highest precision clock available on the system. You can adjust the duration cast to other units like std::chrono::milliseconds or std::chrono::seconds based on your needs.

Remember to compile with optimization flags (e.g., -O2 or -O3) to get accurate timing results, as debug builds may introduce additional overhead.

Answers to questions are automatically generated and may not have been reviewed.

Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved