0

对于下面的代码,我有时会得到负值。我不明白这一点。任何人都可以解释为什么会发生这种情况。

int64_t gettimelocal()
{
    struct timeval Time;
    if(-1 == gettimeofday(&Time,NULL))
    {
        perror("gettimeofday");
    }
    // get time in micro seconds 
    return ((Time.tv_sec * 1000000) + Time.tc_usec);
}
4

1 回答 1

1

To be safe, you should initialize Time. When getttimeofday fails, you should return after the perror. So try:

int64_t gettimelocal() {
   struct timeval Time = {0,0};
   if(-1 == gettimeofday(&Time,NULL)) {
     perror("gettimeofday");
     return -1;
   }
   // get time in micro seconds 
   return (((int64_t)Time.tv_sec * 1000000) + Time.tv_usec);
}

At last, are you sure that the multiplication does not overflow? You want a cast to be sure the multiplication is done in 64 bits.

Actually, I would suggest using double floating point with clock_gettime(3) like this:

static inline double my_clock_time (clockid_t cid) {
  struct timespec ts = { 0, 0 };
  if (clock_gettime (cid, &ts))
     return NAN;
  else
    return (double) ts.tv_sec + 1.0e-9 * ts.tv_nsec;
}

and call my_clock_time(CLOCK_REALTIME) like

 printf ("now %.5f\n", my_clock_time(CLOCK_REALTIME));

Read carefully time(7). Don't expect nanosecond accuracy!

Compile your code with all warnings and debug info (e.g. gcc -Wall -g). Use the debugger (gdb) and perhaps strace(1)

于 2014-09-01T11:44:21.857 回答