简体   繁体   English

在Linux上运行的C ++程序中计时功能

[英]Timing a function in a C++ program that runs on Linux

I am trying to time a function of my C++ program using the amount of time that it takes to execute in user space. 我正在尝试使用在用户空间中执行所需的时间来计时C ++程序的功能。 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. 我从程序内部尝试了clock_gettime(CLOCK_PROCESS_CPUTIME_ID,&start)命令,但恐怕这是CPU时间,而不是我实际需要的用户时间。 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 使用times()函数,请参见: 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). 您还可以使用诸如gprof之类的探查器,它将自动为您完成所有操作(但会产生开销)。

Try the boost:timer library. 尝试boost:timer库。 It is portable and easy to use. 它是便携式的,易于使用。 The Boost timers separately give you wall clock time, user time and system time. Boost计时器分别为您提供挂钟时间,用户时间和系统时间。

http://www.boost.org/doc/libs/1_53_0/libs/timer/doc/cpu_timers.html http://www.boost.org/doc/libs/1_53_0/libs/timer/doc/cpu_timers.html

You could use gettimeofday() as exemplified here . 您可以使用此处例举的gettimeofday()。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM