c++ measure time of function
To measure the time taken by a function in C++, you can use the
- Include the
header file:
#include <chrono>
- Declare variables to hold the start and end time points:
std::chrono::steady_clock::time_point start, end;
- Get the start time point before the function execution:
start = std::chrono::steady_clock::now();
Call the function whose execution time you want to measure.
Get the end time point after the function execution:
end = std::chrono::steady_clock::now();
- Calculate the duration by subtracting the start time point from the end time point:
std::chrono::duration<double> duration = end - start;
- 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.