0

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:

  1. Adding a new function to time is as simple as referencing a macro
  2. 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.

James
  • 703
  • 1
  • 7
  • 22
  • Possible duplicate of [Easily measure elapsed time](https://stackoverflow.com/questions/2808398/easily-measure-elapsed-time) – TimD1 Mar 28 '18 at 14:56
  • 1
    make the macro declare a static and a local (different classes) in each method, pass the static as a parameter to the local and use the static to keep the accumulated time, in the static destructor you log the sum – Erik Elmgren Mar 28 '18 at 14:57
  • 1
    Just use profiler – Slava Mar 28 '18 at 15:02
  • 1
    Do you intend to use the timing data within your program for anything besides reporting it ? If not, you should use a profiler, which does not modify the code. If using GCC, compile your program with the -pg flag, then run it. Profiling data will be written to gmon.out. You can read a report of the execution with "gprof program-binary gmon.out". Visual Studio also has a profiler, google visual studio profiling to get the docs on it. – FBergo Mar 28 '18 at 15:03
  • Thanks for everyone commented. I decided to use the method mentioned by Erik Elmgren to solve the problem. A profiler might not be a right tool for me. Because I am interested in how some certain parts perform when processing some real data. Since running the whole program is expensive(hundreds of CPU hours), I am afraid if adding profiling instructions everywhere is a good idea. – James Mar 28 '18 at 15:16

0 Answers0