问题描述
我正在写一个套接字程序维持FIFO队列两输入插孔。在决定哪个队列服务时,该程序提取从每个队列的最近时间戳。
I'm writing a socket program that maintains FIFO queues for two input sockets. When deciding which queue to service, the program pulls the most recent time-stamp from each queue.
我需要比较两个的timeval
结构的可靠方法。我试着用 timercmp()
,但是我的gcc版本不支持它,文档指出功能没有与POSIX兼容。
I need a reliable method for comparing two timeval
structs. I tried using timercmp()
, but my version of gcc doesn't support it, and documentation states that the function is not POSIX compliant.
我应该怎么办?
推荐答案
谷歌上搜索的timeval
提供的。从该页面:
googling timeval
give this first result. From that page:
通常需要减去类型timeval结构或结构的timespec的两个值。下面是做到这一点的最好办法。它的工作原理甚至在一些特殊的操作系统,其中tv_sec成员有一个无符号类型。
It is often necessary to subtract two values of type struct timeval or struct timespec. Here is the best way to do this. It works even on some peculiar operating systems where the tv_sec member has an unsigned type.
/* 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;
}
这篇关于我如何比较C两个时间戳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!