1
votes

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
Have you considered using a profiler like gprof?linuxuser27
what is gprof, and how do i use it?Joe Shmo

3 Answers

5
votes

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

1
votes

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;
1
votes

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