Measuring execution time with <chrono>

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

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.

Odds and Ends: 10 Useful Techniques

A quick tour of ten useful techniques in C++, covering dates, randomness, attributes and more

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

When to use std::vector vs std::array
When should I use std::vector and when should I use std::array in C++?
Choosing the right random number distribution
How do I choose the appropriate random number distribution for my use case?
Using [[nodiscard]] with custom types
How can I use the [[nodiscard]] attribute with my own custom types?
Creating a custom ClangFormat style
How can I create a custom ClangFormat style for my C++ project?
Integrating static analysis tools into your workflow
How can I integrate static analysis tools like Cppcheck into my C++ development workflow?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant