C struct timeval timersub()负值为正

时间:2013-07-05 18:02:32

标签: c time timer

我正在使用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中。

1 个答案:

答案 0 :(得分:2)

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

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);
}