如何比较C中的两个时间戳?

Vis*_*ota 11 c sockets timestamp timeval

我正在编写一个套接字程序来维护两个输入套接字的FIFO队列.在决定要服务的队列时,程序从每个队列中提取最新的时间戳.

我需要一种可靠的方法来比较两个timeval结构.我尝试使用timercmp(),但我的gcc版本不支持它,文档说明该功能不符合POSIX.

我该怎么办?

Gon*_*alo 12

timercmp() 只是libc中的一个宏(sys/time.h):

# define timercmp(a, b, CMP)                                                  \
  (((a)->tv_sec == (b)->tv_sec) ?                                             \
   ((a)->tv_usec CMP (b)->tv_usec) :                                          \
   ((a)->tv_sec CMP (b)->tv_sec))
Run Code Online (Sandbox Code Playgroud)

如果您需要timersub():

# define timersub(a, b, result)                                               \
  do {                                                                        \
    (result)->tv_sec = (a)->tv_sec - (b)->tv_sec;                             \
    (result)->tv_usec = (a)->tv_usec - (b)->tv_usec;                          \
    if ((result)->tv_usec < 0) {                                              \
      --(result)->tv_sec;                                                     \
      (result)->tv_usec += 1000000;                                           \
    }                                                                         \
  } while (0)
Run Code Online (Sandbox Code Playgroud)


ASh*_*lly 6

谷歌搜索timeval给出了第一个结果.从该页面:

通常需要减去struct timeval或struct timespec类型的两个值.这是最好的方法.它甚至可以在某些特殊的操作系统上运行,其中tv_sec成员具有无符号类型.

 /* Subtract the `struct timeval' values X and Y,
    storing the result in RESULT.
    Return 1 if the difference is negative, otherwise 0.  */

 int
 timeval_subtract (result, x, y)
      struct timeval *result, *x, *y;
 {
   /* Perform the carry for the later subtraction by updating 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;
   }

   /* Compute the time remaining to wait.
      tv_usec is certainly positive. */
   result->tv_sec = x->tv_sec - y->tv_sec;
   result->tv_usec = x->tv_usec - y->tv_usec;

   /* Return 1 if result is negative. */
   return x->tv_sec < y->tv_sec;
 }
Run Code Online (Sandbox Code Playgroud)

  • 为了澄清,我意识到时间段被初始化为`tv_sec`和`tv_usec`值为0.使用`gettimeofday()`正确初始化队列解决了问题.感谢您的支持.=) (2认同)
  • 只是为了让其他人不会受到我所做的同样的错误,请注意调用此函数有50%的机会修改y参数,导致您传入的时间被修改. (2认同)