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:
- Get the current time point before executing the function using
std::chrono::high_resolution_clock::now()
. - Execute the function you want to measure.
- Get the current time point after the function execution.
- 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