How to measure time intervals in C++

Measuring the time interval of a specific code segment is crucial to determine its execution time. This allows us to assess the impact of that code block on the overall performance of the program and identify areas for improvement.

Measuring time intervals

We can find the time interval of a code block in a C++ program by using the chrono library.

The chrono library contains multiple methods to find and manipulate the system time and retrieve time intervals for code blocks in C++ programs. The std::chrono::high_resolution_clock::now() method gives us the current system time when the line of code was executed.

We can use this function to retrieve the time between two code intervals and then calculate the difference between them to find the execution time for that specific code segment. To do this, we will call the function at the start of the code segment and after execution of the code segment.

Program structure representation
Program structure representation

To find the difference between the two time stamps, we will simply subtract the start and end variables that hold both time stamps.

Code example

As we can see in the example program below, we can find how long the code takes to run a loop of 0 to 100 by applying the function listed above.

#include <iostream>
#include <chrono>
int main() {
// Start the timer
auto start = std::chrono::high_resolution_clock::now();
for(int i = 0; i < 100; i++){};
// End the timer
auto end = std::chrono::high_resolution_clock::now();
// Calculate the duration
std::chrono::duration<double> duration = end - start;
// Print the duration in seconds
std::cout << "Execution time: " << duration.count() << " seconds." << std::endl;
return 0;
}

Advantages of measuring time intervals

Below are some advantages of finding the time intervals of individual code blocks in a C++ program.

  • It can be used to evaluate the performance of the existing code blocks in terms of how much time they took to finish.

  • It allows us to compare different algorithms and select the one which gives us the best performance.

  • It can be used in debugging to analyze the behavior of specific code segments.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved