You can use the <chrono>
library to measure the execution time of a function by following these steps:
std::chrono::high_resolution_clock::now()
.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.
A quick tour of ten useful techniques in C++, covering dates, randomness, attributes and more