質問

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

I know this is not the best function, but I want to understand why. In this question AndrewStone says there'll be a problem twice a yea, I don't understand why would there be a problem if we're just counting microseconds from epoch.

And if I misunderstood the man and the time is the value of the seconds + the microseconds how can I solve this issue?

役に立ちましたか?

解決

gettimeofday takes two arguments:

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

As per the man page:

The use of the timezone structure is obsolete; the tz argument should normally be specified as NULL.

Provided you do this, it will simply return seconds and microseconds since the epoch, i.e. no timezones are involved. Whoever told you differently is wrong in this respect.

However, you still have to be a little careful. Whilst you won't see this advance or retard by an hour, I believe you will find that it advances and retards as wall time is adjusted by things like ntp. So the elapsed number of microseconds between two calls may not be the difference between the two results (if, for instance, ntp is advancing or retarding the clock).

A better route is to use clock_gettime() with CLOCK_REALTIME or CLOCK_MONOTONIC, depending on exactly what you are trying to measure (elapsed time or change in clock).

Edit: you wanted a routine to subtract two timeval structures. Here's one:

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;
}

which is similar to the one here: http://www.gnu.org/software/libc/manual/html_node/Elapsed-Time.html

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top