English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
We can use the following syntax to calculate the execution time of a code snippet:
auto start = high_resolution_clock::now(); // Start time //Code segment auto stop = high_resolution_clock::now(); // Stop time auto duration = duration_cast<microseconds>(stop - start); // Duration
The 'high_resolution_clock' class is defined in the 'chrono' header file. The functionnow()
It is returning a value corresponding to the point of the call.
Header files are used to record the time spent on the specific code.
#include <chrono> using namespace std::chrono;
The following is an example of calculating the execution time of a code segment.
#include <iostream> #include <chrono> using namespace std::chrono; using namespace std; int sum(int x, int y) { int s = x + y; cout << "The sum of numbers: " << s; } int main() { auto start = high_resolution_clock::now(); sum(28, 8); auto stop = high_resolution_clock::now(); auto duration = duration_cast<microseconds>(stop - start); cout << "\nTime taken by function: " << duration.count() << " microseconds"; return 0; }
Output result
The sum of numbers: 36 Time taken by function: 42 microseconds
In the above program,sum()
A function is defined to calculate the sum of numbers.
int sum(int x, int y) { int s = x + y; cout << "The sum of numbers: " << s; }
Inmain()
In the function, wesum()
The time spent on the function is recorded by using some predefined functions and the 'chrono' class.
auto start = high_resolution_clock::now(); sum(28, 8); auto stop = high_resolution_clock::now(); auto duration = duration_cast<microseconds>(stop - start);