首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C struct timeval timersub()负值改为正值

C struct timeval timersub()负值改为正值
EN

Stack Overflow用户
提问于 2013-07-06 02:02:32
回答 1查看 6.9K关注 0票数 0

我正在使用timersub(struct timeval *a, struct timeval *b, struct timeval *res)来按时进行操作。我要做的是,把一个较高的值减去一个较低的值,得到负值的时间差。

例如:

代码语言:javascript
复制
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中。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-06 03:55:01

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

代码语言:javascript
复制
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);
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17494589

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档