How to calculate Execution Time of a Code Snippet in C++?


We can calculate the execution time of a code snippet by using following syntax −

auto start = high_resolution_clock::now(); // Start time
// Code snippet
auto stop = high_resolution_clock::now(); // Stop time
auto duration = duration_cast<microseconds>(stop - start); // Duration

The class high_resolution_clock is defined in “chrono” header file. The function now() is returning a value corresponding to the call’s point in time.

A header file is used to record the time taken by that particular code.

#include <chrono>
using namespace std::chrono;

The following is an example to calculate execution time of a code snippet.

Example

 Live Demo

#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

The sum of numbers : 36
Time taken by function : 42 microseconds

In the above program, a function sum() is defined to calculate the sum of numbers.

int sum(int x, int y) {
   int s = x + y;
   cout << "The sum of numbers : " << s;
}

In the main() function, we recorded the time taken by the function sum() by using some predefined functions and class “chrono”.

auto start = high_resolution_clock::now();
sum(28, 8);
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 26-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements