I'd like to time how long a function takes in C++ in milliseconds.
Here's what I have:
#include<iostream>
#include<chrono>
using timepoint = std::chrono::steady_clock::time_point;
float elapsed_time[100];
// Run function and count time
for(int k=0;k<100;k++) {
// Start timer
const timepoint clock_start = chrono::system_clock::now();
// Run Function
Recursive_Foo();
// Stop timer
const timepoint clock_stop = chrono::system_clock::now();
// Calculate time in milliseconds
chrono::duration<double,std::milli> timetaken = clock_stop - clock_start;
elapsed_time[k] = timetaken.count();
}
for(int l=0;l<100;l++) {
cout<<"Array: "<<l<<" Time: "<<elapsed_time[l]<<" ms"<<endl;
}
This compiles but I think multithreading is preventing it from working properly. The output produces times in irregular intervals, e.g.:
Array: 0 Time: 0 ms
Array: 1 Time: 0 ms
Array: 2 Time: 15.6 ms
Array: 3 Time: 0 ms
Array: 4 Time: 0 ms
Array: 5 Time: 0 ms
Array: 6 Time: 15.6 ms
Array: 7 Time: 0 ms
Array: 8 Time: 0 ms
Do I need to use some kind of mutex lock? Or is there an easier way to time how many milliseconds a function took to execute?
EDIT
Maybe people are suggesting using high_resolution_clock
or steady_clock
, but all three produce the same irregular results.
This solution seems to produce real results: How to use QueryPerformanceCounter? but it's not clear to me why. Also, https://gamedev.stackexchange.com/questions/26759/best-way-to-get-elapsed-time-in-miliseconds-in-windows works well. Seems to be a Windows implementation issue.