I am trying to time a function of my C++ program using the amount of time that it takes to execute in user space. I tried the clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start) command from inside the program but I am afraid that this is the CPU time and not the User Time that I actually need. The time "program name" will not work in this case because I am only timing a function. Any help would be great. Thanks!
3 Answers
Use the times() function, see: http://linux.die.net/man/2/times
This will give you current user and system time for your process. You can call it on entry and exit from your subroutine, and subtract.
You can also use a profiler like gprof, which will do this all automatically for you (but will incur overhead).
3 Comments
times seems the perfect solution. The overhead of gprof isn't IMO that little and moreover instrumented code can behave quite differently for caching issues. Especially for fast code IMO the only way to get reasonable numbers are passive statistical profilers.You could use gettimeofday() as exemplified here.
Add this function to your code:
#include <sys/time.h> long myclock() { struct timeval tv; gettimeofday(&tv, NULL); return (tv.tv_sec * 1000000) + tv.tv_usec; } and use it to retrieve the time:
long start = myclock(); // do something // ... long end = myclock() - start; std::cout << "[" << time->tm_hour << ":"<< time->tm_min << ":" << time->tm_sec << "] time:" << std::setprecision(3) << end/1000000.0 << std::endl; 2 Comments
Try the boost:timer library. It is portable and easy to use. The Boost timers separately give you wall clock time, user time and system time.
http://www.boost.org/doc/libs/1_53_0/libs/timer/doc/cpu_timers.html
gprof?