0

我习惯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 中。

4

1 回答 1

3

检查哪个时间值更大以确定提供操作数的顺序:

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);
}
于 2013-07-05T19:55:01.447 回答