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

C++ProgrammingServer Side Programming

C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

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 << "Time 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);
Updated on 26-Jun-2020 09:14:20