Calculate Execution Time of Code Snippet in C++



To calculate the execution time of a program, use the std::chrono library, which was introduced in C++11. This library has two distinct objects: time_point and duration. The time_point represents the variable names that store the start and end times of specific algorithms, functions, or loops used in the program. While duration represents the interval between two different times. The chrono library allows us to subtract these time intervals. Here, we use the high_resolution_clock::now() function, which provides accurate units of time.

Calculate the Execution Time of a C++ Program

To get the execution time of a program use the chrono header that gives access to the clock and functionality like clock and duration. Then proceed with the calculation of start and end time with the help of high_resolution_clock::now() in which you have to pass something (eg. for loop) for total time execution. Next, duration_cast<microseconds> converts the time difference into microseconds while using count(), we get the exact numeric value.

Syntax

Its syntax is as follows:

high_resolution_clock::now()

Here,

  • high_resolution_clock::now() : It is used to get the current timing.
duration_cast

Here,

  • The duration_cast is used to calculate the time based on one unit of time to another. For example, second to milliseconds, microseconds, etc.

Example

In this example, we print the time of a code snippet using C++.

#include <iostream>

// header file required for timing
#include <chrono> 

using namespace std;
using namespace std::chrono;

int main() {
    // Start the timer
    auto start = high_resolution_clock::now();

    // This is the loop to measure the times
    for (int i = 0; i < 1000000; ++i);

    // End the timer
    auto end = high_resolution_clock::now();

    // Calculate duration
    auto duration = duration_cast < microseconds > (end - start);

    cout << "Execution time: " << duration.count() << " microseconds" << endl;

    return 0;
}

Output (Machine Dependent)

The above program produces the following result:

Execution time: 367 microseconds
Updated on: 2025-05-02T18:01:54+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements