time measurement c++

To measure the time taken by a piece of code in C++, you can use the <chrono> library. This library provides a high-resolution clock that can be used to measure time accurately.

Here are the steps to measure time in C++ using the <chrono> library:

  1. Include the <chrono> header file in your program:
#include <chrono>
  1. Declare the variables to store the start and end times:
std::chrono::high_resolution_clock::time_point start_time, end_time;
  1. Record the start time using the now() function:
start_time = std::chrono::high_resolution_clock::now();
  1. Execute the code whose execution time you want to measure.

  2. Record the end time using the now() function:

end_time = std::chrono::high_resolution_clock::now();
  1. Calculate the duration by subtracting the start time from the end time:
std::chrono::duration<double> duration = end_time - start_time;
  1. Convert the duration to the desired time unit (e.g., seconds, milliseconds, microseconds) using the appropriate function from the <chrono> library:
double time_taken = duration.count();
  1. Print the time taken:
std::cout << "Time taken: " << time_taken << " seconds" << std::endl;

That's it! You have now measured the time taken by a piece of code in C++ using the <chrono> library.

Here's a complete example:

#include <iostream>
#include <chrono>

int main() {
    std::chrono::high_resolution_clock::time_point start_time, end_time;

    start_time = std::chrono::high_resolution_clock::now();

    // Code to measure the time here

    end_time = std::chrono::high_resolution_clock::now();

    std::chrono::duration<double> duration = end_time - start_time;
    double time_taken = duration.count();

    std::cout << "Time taken: " << time_taken << " seconds" << std::endl;

    return 0;
}

This example measures the time taken to execute the code between start_time and end_time and prints the result in seconds.