C struct timeval timersub()负值为正。

时间:2021-04-25 22:53:03

I'm using timersub(struct timeval *a, struct timeval *b, struct timeval *res) to make operation on time. And what I would to do is, substract a higher value to a lower value and get the difference of time which is in the negative.

我使用timersub(struct timeval *a, struct timeval *b, struct timeval *res)来按时完成操作。我要做的是,把一个更大的值减去一个更低的值然后得到时间的差值是负的。

For example :

例如:

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

The output is : RES : Secondes : -1 Microseconds: 999999

输出是:RES: Secondes: -1微秒:999999。

What I would like to have is : RES : Secondes : 0 Microseconds: 1

我想要的是:RES:秒:0微秒:1 !

Does someone have any idea of the trick ? I'd like to store the result in a struct timeval too.

有人知道这个把戏吗?我也想把结果存储在struct timeval中。

1 个解决方案

#1


2  

Check which time value is bigger to determine which order to provide the operands:

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

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

#1


2  

Check which time value is bigger to determine which order to provide the operands:

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

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