1

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!

Joe Shmo
  • 57
  • 2
  • 3

3 Answers3

5

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).

payne
  • 13,833
  • 5
  • 42
  • 49
  • 1
    +1: `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. – 6502 Feb 19 '11 at 21:24
  • when I use times() and get the user time I get a value of 0. Doesnt that mean that my function is running too fast for it to time the function? – Joe Shmo Feb 20 '11 at 19:35
  • That may be the case. times() returns a count of "clock ticks", and you have to call sysconf(_SC_CLK_TCK) to figure out what the tick period is on your system. See the times man page. – payne Feb 21 '11 at 01:49
1

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

Sameer
  • 2,435
  • 23
  • 13
1

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;
Community
  • 1
  • 1
karlphillip
  • 92,053
  • 36
  • 243
  • 426
  • Doesn't that measure wall-clock time rather than user-space CPU time? Your approach is what I generally use, but it is slightly different from the question seems to be asking. It also isn't clear if the result required is 'only this function' or 'this function and those it calls'. – Jonathan Leffler Feb 19 '11 at 21:32
  • The main problem on a system with hundreds of processes running is that you cannot know whether you were swapped out. So this method will really only work if your function is very fast and somehow your process doesn't get swapped for another while timing your function. – Alexis Wilke Dec 27 '12 at 00:28