为什么getTimeofday()间隔偶尔会负面?
-
03-10-2019 - |
题
我有一个实验库,我正在尝试测量其性能。为此,我写了以下内容:
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
这是怎么回事?
解决方案
你有一个错别字。更正的最后一行(注意0s的数量):
std::cout << "Time: " << 1000000 * (end.tv_sec - begin.tv_sec) + (end.tv_usec - begin.tv_usec) << std::endl;
顺便提一句, timersub
是一种内置的方法,可以获得两个时空之间的差异。
其他提示
std :: cout <<“时间:” << 100000 *(end.tv_sec- begin.tv_sec) +(end.tv_usec -begin.tv_usec)<< std :: endl;
如前所述,SEC中有1000000 USEC,而不是100000。
更一般而言,您可能需要意识到计算机上计时的不稳定。诸如 ntpd
可以更改时钟时间,导致三角洲不正确。您可能对Posix设施感兴趣,例如 timer_create
.
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 Crystal或其他),因此通常比 gettimeofday()
. 。同样,即使NTPD或用户在系统时间愚蠢的情况下,单调计时器也永远不会向后移动。
您照顾了负值,但仍然不正确。毫秒变量之间的差异是错误的,例如我们开始和结束时间为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);
做
$ time ./proxy-application
下次
不隶属于 StackOverflow