Measure Execution Time With High Precision In C++ - C++ Programming Tutorial
C++ Course / Miscellaneous / Measure Execution Time With High Precision In C++

Measure Execution Time With High Precision In C++

BLUF: Mastering Measure Execution Time With High Precision In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Measure Execution Time With High Precision In C++

C++ is renowned for its efficiency. Learn how Measure Execution Time With High Precision In C++ enables low-level control and high-performance computing in the tutorial below.

In numerous software programs, accurately determining execution time is crucial, especially when fine-tuning code or assessing the efficiency of different algorithms.

In order to accurately gauge execution duration in C++, it is essential to capture and calculate time spans utilizing the <chrono> library introduced in C++11. The <chrono> library provides a variety of clock types and time-related tools, designed to offer superior accuracy and compatibility compared to traditional C-style time functions. Various functions within C++ are employed to measure execution time with exceptional precision.

1. Clock Types

The <chrono> library offers various clock types such as std::chrono::steadyclock, std::chrono::highresolutionclock, and std::chrono::systemclock. The highresolutionclock is commonly selected for measuring execution time due to its superior precision on the system.

2. Time Points

Clock functions are essential for retrieving time points and specific instances in time. To measure the duration of executing a code segment, it is crucial to record the beginning and ending timestamps.

Example

auto start_time = std::chrono::high_resolution_clock::now();
//Code to measure goes here
auto end_time = std::chrono::high_resolution_clock::now();

3. Duration

The contrast between two time points is depicted as a duration. It calculates the time passed between the start and end of the code segment.

4. Units of Duration

Depending on our needs, we have the option to choose a time measurement unit like milliseconds, seconds, or microseconds.

Example

auto duration_micro = std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time);
auto duration_milli = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);
auto duration_sec = std::chrono::duration_cast<std::chrono::seconds>(end_time - start_time);

5. Precision and Portability

While it typically quantifies in nanoseconds or shorter durations, the accuracy of <chrono> is determined by the specific implementation.

Due to its cross-platform and cross-compiler compatibility, the library functions reliably.

6. Advantages:

  • Precision: Measurements can be made more accurately because <chrono> is more precise than conventional C time functions.
  • Portability: The library can measure execution time on various systems because of its platform-independent nature.
  • Consistency: By guaranteeing consistent behaviour across platforms and compilers, time measurement inconsistencies are less likely.
  • Ease of Use: Integrating high-precision timing into our C++ code is reasonably accessible because of the simple syntax.
  • 7. Use Cases:

  • Performance Profiling: Locate bottlenecks and enhance crucial code segments.
  • Algorithm Comparison: Compare the efficiency of different algorithms by measuring their execution times.
  • Real-time systems: Make sure that, in real-time applications, specific processes are completed within predetermined time limits.
  • Example:

Let's consider a scenario to demonstrate how to accurately calculate the elapsed time in C++.

Example

#include <iostream>
#include <chrono>
int main()
{
    // Capture the start time point
    auto start_time = std::chrono::high_resolution_clock::now();
    //Code to measure execution time goes here
    for (int i = 0; i < 1000000; ++i)
    {
        // Some computation-intensive operation
        int result = i * i;
    }
    // Capture the end time point
    auto end_time = std::chrono::high_resolution_clock::now();
    // Calculate the duration between start and end time points
    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time);
    // Print the execution time in microseconds
    std::cout << "Execution Time: " << duration.count() << " microseconds" << std::endl;
    return 0;
}

Output:

Output

Execution Time: 1152 microseconds

Explanation:

  1. Include Required Headers

The input/output operations (<iostream>) and high-precision timing functionality (<chrono>) require the headers that are included in these lines.

  1. Capture Start Time

In this scenario, the present moment is acquired by utilizing std::chrono::highresolutionclock::now and stored in the variable start_time. The duration of execution can then be computed from this particular instant onwards.

  1. Code for Determining Execution Duration

This loop emulates a computationally intensive task, serving as a placeholder for the actual code under evaluation. Hence, the intricacies of the task are non-essential for time measurement purposes.

  1. Record Finish Time

Similar to the initial time recording, this line stores the present time within the variable end_time. This marks the conclusion of the code block we wish to measure the execution duration of.

  1. Compute Time Span

The std::chrono::durationcast function is employed to calculate the duration between starttime and end_time, which is then converted to microseconds for better readability.

  1. Display Time Taken

Ultimately, the calculation of execution time is displayed on the console. The time interval is obtained in microseconds by utilizing the duration.count method.

  1. Exit with a return value of 0.

To inform the operating system that the program has executed without errors, the main function returns a value of 0.

Conclusion:

In summary, the code captures the start and end times of a task that requires significant computational resources, calculates the duration between them, and displays the elapsed time in microseconds on the console. This provides a foundational structure that can be adjusted to measure the execution duration of specific segments within a C++ program.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience