【问题标题】:gettimeofday() returns negative value some timesgettimeofday() 有时会返回负值
【发布时间】:2014-09-01 11:38:22
【问题描述】:

以下代码有时会得到负值。 我不明白。任何人都可以解释为什么会发生这种情况。

int64_t gettimelocal()
{
    struct timeval Time;
    if(-1 == gettimeofday(&Time,NULL))
    {
        perror("gettimeofday");
    }
    // get time in micro seconds 
    return ((Time.tv_sec * 1000000) + Time.tc_usec);
}

【问题讨论】:

  • 请通过编辑更好地格式化您的问题。这是不可读的!使用以至少四个空格开头的行作为代码。
  • (Time.tv_sec * 1000000)
  • 如何显示? %d?尝试 %ld 或类似的东西。
  • 抱歉,这是拼写错误。我只使用 Time.tv_usec。 perror("gettimeofday");不会显示任何错误。
  • 我用"%"PRId64"显示,为什么一直没有溢出?

标签: linux gettimeofday


【解决方案1】:

为了安全起见,您应该初始化Time。当getttimeofday 失败时,您应该在perror 之后返回。所以试试:

int64_t gettimelocal() {
   struct timeval Time = {0,0};
   if(-1 == gettimeofday(&Time,NULL)) {
     perror("gettimeofday");
     return -1;
   }
   // get time in micro seconds 
   return (((int64_t)Time.tv_sec * 1000000) + Time.tv_usec);
}

最后,你确定乘法不会溢出吗?您需要强制转换以确保乘法以 64 位完成。

实际上,我建议像这样使用double 浮点和clock_gettime(3)

static inline double my_clock_time (clockid_t cid) {
  struct timespec ts = { 0, 0 };
  if (clock_gettime (cid, &ts))
     return NAN;
  else
    return (double) ts.tv_sec + 1.0e-9 * ts.tv_nsec;
}

并致电my_clock_time(CLOCK_REALTIME) 喜欢

 printf ("now %.5f\n", my_clock_time(CLOCK_REALTIME));

仔细阅读time(7)。不要指望纳秒级的精度!

使用所有警告和调试信息(例如gcc -Wall -g)编译您的代码。使用调试器 (gdb) 或者 strace(1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-23
    • 1970-01-01
    • 2012-01-26
    • 1970-01-01
    • 2015-06-02
    • 2018-05-07
    • 2023-01-08
    相关资源
    最近更新 更多