6

我有一个实验库,我正在尝试测量其性能。为此,我编写了以下内容:

struct timeval begin;
gettimeofday(&begin, NULL);
{
    // Experiment!
}
struct timeval end;
gettimeofday(&end, NULL);

// Print the time it took!
std::cout << "Time: " << 100000 * (end.tv_sec - begin.tv_sec) + (end.tv_usec - begin.tv_usec) << std::endl;

有时,我的结果包括负时间,其中一些是荒谬的。例如:

Time: 226762
Time: 220222
Time: 210883
Time: -688976

这是怎么回事?

4

5 回答 5

6

你有一个错字。更正了最后一行(注意 0 的数量):

std::cout << "Time: " << 1000000 * (end.tv_sec - begin.tv_sec) + (end.tv_usec - begin.tv_usec) << std::endl;

顺便说一句,timersub是一种内置方法来获取两个时间间隔之间的差异。

于 2010-05-06T10:35:55.307 回答
4

posix 实时库更适合测量高精度间隔。你真的不想知道当前时间。您只想知道两点之间的时间。这就是单调时钟的用途。

struct timespec begin;
clock_gettime( CLOCK_MONOTONIC, &begin );
{
    // Experiment!
}
struct timespec end;
clock_gettime(CLOCK_MONOTONIC, &end );

// Print the time it took!
std::cout << "Time: " << double(end.tv_sec - begin.tv_sec) + (end.tv_nsec - begin.tv_nsec)/1000000000.0 << std::endl;

当您链接时,您需要添加-lrt.

使用单调时钟有几个优点。它通常使用硬件定时器(Hz 晶体或其他),因此它通常比gettimeofday(). 即使 ntpd 或用户在使用系统时间,也可以保证单调计时器永远不会倒退。

于 2010-05-06T15:03:24.670 回答
3

您处理了负值,但它仍然不正确。毫秒变量之间的差异是错误的,例如我们将开始时间和结束时间分别设置为 1.100 秒和 2.051 秒。根据公认的答案,这将是 1.049 秒的经过时间,这是不正确的。

下面的代码处理了只有毫秒而不是秒的差异以及毫秒值溢出的情况。

if(end.tv_sec==begin.tv_sec)
printf("Total Time =%ldus\n",(end.tv_usec-begin.tv_usec));
else
printf("Total Time =%ldus\n",(end.tv_sec-begin.tv_sec-1)*1000000+(1000000-begin.tv_usec)+end.tv_usec);
于 2014-07-18T19:51:07.917 回答
3

std::cout << "时间:" << 100000 * (end.tv_sec - begin.tv_sec) + (end.tv_usec - begin.tv_usec) << std::endl;

如前所述,每秒有 1000000 usec,而不是 100000。

更一般地说,您可能需要注意计算机上计时的不稳定性。诸如ntpd可以更改时钟时间的进程,导致不正确的增量时间。您可能对 POSIX 工具感兴趣,例如timer_create.

于 2010-05-06T10:38:59.683 回答
-1

$ time ./proxy-application

下次

于 2010-05-06T12:04:02.663 回答