I want to measure the total time spent in some functions. Currently the best solution I can come up with is:
#include<map>
#include<iostream>
#include<chrono>
using namespace std;
map<const char*,double> time_data;
struct time_class{
const char*const name;
chrono::high_resolution_clock::time_point t1=chrono::high_resolution_clock::now();
time_class(const char*const name):name{name}{}
~time_class(){
chrono::high_resolution_clock::time_point t2=chrono::high_resolution_clock::now();
time_data[name]+=chrono::duration_cast<chrono::duration<double>>(t2 - t1).count();
}
};
#define TIMEME time_class time_class_var(__func__);
void f(){
TIMEME
}
struct X{
void g(){
TIMEME
}
};
int main(){
X x;
f();
x.g();
for(auto&x:time_data)
cout<<x.first<<' '<<x.second<<'\n';
}
The measure part is very easy to use, but the use of std::map
adds runtime overhead.
Alternatively, I can write function specific code to declare variables and obtain the best performance.
I wander if there is a way:
- Adding a new function to time is as simple as referencing a macro
- Time complexity for additional code executed for each function call is guaranteed constant(except the first one for the possible initialization purpose)
I considered to use a template, but it seems there's no way to pass the function name to a template without writing specific code for each function.