开发者

Timing a function in a C++ program that runs on Linux

开发者 https://www.devze.com 2023-02-11 06:30 出处:网络
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) comman

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!


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


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;


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

0

精彩评论

暂无评论...
验证码 换一张
取 消