Understanding the gettimeofday system call

I need to use gettimeofday to measure the time differences in microsecond resolution using this function.

I know that this is not the best function, but I want to understand why. In this question, AndrewStone says that there will be a problem twice , yes, I don’t understand why the problem would have occurred simply by counting microseconds from the era.

And if I misunderstood a person, and time is the value of seconds + microseconds, how can I solve this problem?

+3
source share
1 answer

gettimeofday accepts two arguments:

int gettimeofday(struct timeval *tv, struct timezone *tz);

According to the man page:

Use of structure timezoneis deprecated; the argument tzshould usually be specified as NULL.

, , .. . , -, .

. , , , , , ntp. , (, , ntp ).

clock_gettime() CLOCK_REALTIME CLOCK_MONOTONIC, , ( ).

: timeval. :

int
timeval_subtract (struct timeval *result, struct timeval *x,
                  struct timeval *y)
{
  if (x->tv_usec < y->tv_usec)
    {
      int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
      y->tv_usec -= 1000000 * nsec;
      y->tv_sec += nsec;
    }

  if (x->tv_usec - y->tv_usec > 1000000)
    {
      int nsec = (x->tv_usec - y->tv_usec) / 1000000;
      y->tv_usec += 1000000 * nsec;
      y->tv_sec -= nsec;
    }

  result->tv_sec = x->tv_sec - y->tv_sec;
  result->tv_usec = x->tv_usec - y->tv_usec;

  return x->tv_sec < y->tv_sec;
}

: http://www.gnu.org/software/libc/manual/html_node/Elapsed-Time.html

+4

All Articles