我正在使用timersub(struct timeval *a, struct timeval *b, struct timeval *res)来按时进行操作。我要做的是,把一个较高的值减去一个较低的值,得到负值的时间差。
例如:
int main()
{
struct timeval left_operand;
struct timeval right_operand;
struct timeval res;
left_operand.tv_sec = 0;
left_operand.tv_usec = 0;
right_operand.tv_sec = 0;
right_operand.tv_usec = 1;
timersub(&left_operand, &right_operand, &res);
printf("RES : Secondes : %ld\nMicroseconds: %ld\n\n", res.tv_sec, res.tv_usec);
return 0;
}输出为:RES : Secondes : -1 Microseconds: 999999
我想要的是:RES : Secondes : 0 Microseconds: 1
有没有人知道这个诀窍?我也希望将结果存储在struct timeval中。
发布于 2013-07-06 03:55:01
检查哪个时间值较大,以确定提供操作数的顺序:
if (left_operand.tv_sec > right_operand.tv_sec)
timersub(&left_operand, &right_operand, &res);
else if (left_operand.tv_sec < right_operand.tv_sec)
timersub(&right_operand, &left_operand, &res);
else // left_operand.tv_sec == right_operand.tv_sec
{
if (left_operand.tv_usec >= right_operand.tv_usec)
timersub(&left_operand, &right_operand, &res);
else
timersub(&right_operand, &left_operand, &res);
}https://stackoverflow.com/questions/17494589
复制相似问题