c++ measure time of function

To measure the time taken by a function in C++, you can use the library. Here are the steps to do it:

  1. Include the header file:
#include <chrono>
  1. Declare variables to hold the start and end time points:
std::chrono::steady_clock::time_point start, end;
  1. Get the start time point before the function execution:
start = std::chrono::steady_clock::now();
  1. Call the function whose execution time you want to measure.

  2. Get the end time point after the function execution:

end = std::chrono::steady_clock::now();
  1. Calculate the duration by subtracting the start time point from the end time point:
std::chrono::duration<double> duration = end - start;
  1. Extract the duration in seconds:
double durationInSeconds = duration.count();

Now, the durationInSeconds variable will hold the time taken by the function in seconds. You can use this value for further analysis or display purposes.

Here's a complete example:

#include <chrono>
#include <iostream>

void myFunction()
{
    // Function code here
}

int main()
{
    std::chrono::steady_clock::time_point start, end;

    start = std::chrono::steady_clock::now();

    myFunction();

    end = std::chrono::steady_clock::now();

    std::chrono::duration<double> duration = end - start;
    double durationInSeconds = duration.count();

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

    return 0;
}

This code measures the time taken by the myFunction function and prints it to the console. You can replace myFunction with the name of the function you want to measure.