c++ measure the time of a function that is repeatedly called -
in following code, how measure total elapsed time of function1()
, function3()
?
in real situation, function1()
, function3()
scattered everywhere in complex program. need can use name of function start , stop timer
in end can print out how long each function takes in total.
please note time elasped of function1()
not needed value. total time elasped of function1()
called everywhere many times needed value.
int function1() { int = 1; i++; return i; } int function2() { int = 1; i++; return i; } int function3() { int = 1; i++; return i; } int main(int argc, char *argv[]) { size_t t = 0; while (t < 1000000) { // want starttimer(function1) function1(); // want pausetimer(function1) function2(); // want starttimer(function3) function3(); // want pausetimer(function3) } // printtimer() here print total elapsed time of function 1 , //function 3 getchar(); return 0; }
running profiler best way it, if can't reason, following:
1) temporarily rename function1()'s implementation e.g. function1_implementation() (or similar)
2) write new temporary implementation of function1() this:
static unsigned long long totalmicrosinfunction1 = 0; // returns current system-clock-time, in microseconds static unsigned long long get_current_time_in_microseconds() { // may not best way implement function; see below struct timeval tv; gettimeofday(&tv, null); return ((unsigned long long)tv.tv_sec)*1000000 + tv.tv_usec; } int function1() { unsigned long long starttime = get_current_time_in_microseconds(); int ret = function1_implementation(); // call real code! unsigned long long endtime = get_current_time_in_microseconds(); totalmicrosinfunction1 += (endtime-starttime); return ret; }
3) same sort of trick other functions want time.
... recompile program, , @ end of main(), print out current value of totalmicrosinfunction1.
note above implementation of get_current_system_time_in_microseconds() may not best 1 use-case; if you're using c++11, can use std::chrono::high_resolution_clock purpose instead; otherwise use os-specific api queryperformancecounter() under windows.
Comments
Post a Comment