Why are gettimeofday () intervals sometimes negative?

I have an experimental library whose performance I'm trying to measure. For this, I wrote the following:

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;

Sometimes my results include negative timings, some of which are pointless. For instance:

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

What's happening?

+5
source share
5 answers

You have a typo. The last line is fixed (note the number 0s):

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

BTW, timersubis a built-in method for getting the difference between two time intervals.

+7
source

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

, 100 000 000 , 100000.

. , ntpd, , . POSIX, timer_create.

+3

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.

. ( - ), , gettimeofday(). , ntpd .

+3

, . , , 1.100s 2.051s. 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);
+2
source

do

$ time ./proxy-application

next

-1
source

All Articles