【问题标题】:Better way to get absolute time?获得绝对时间的更好方法?
【发布时间】:2015-04-17 12:20:33
【问题描述】:

目前我正在尝试获得与pthread_mutex_timedlock 一起使用的绝对时间。我知道我需要将gettimeofday 中的timeval 添加到timespec,然后添加我的任意时间。

以下方法有效,但与如此大的数字相乘时可能会溢出。

有没有更好的方法来做到这一点(我给出了一个以毫秒为单位的时间):

struct timespec ts;
struct timeval now;
gettimeofday(&now, nullptr);

ts.tv_sec = now.tv_sec + milliseconds / 1000;
ts.tv_nsec = now.tv_usec * 1000000000 * (milliseconds % 1000);

ts.tv_sec += ts.tv_nsec / (1000000000);
ts.tv_nsec %= (1000000000);

在上面,我将给定的时间与当前时间相加得到一个绝对时间。

我的替代代码是:

void timeval_to_timespec(struct timeval* tv, struct timespec* ts)
{
    ts->tv_sec = tv->tv_sec;
    ts->tv_nsec = tv->tv_usec * 1000;
}

struct timespec add_timespec(struct timespec* a, struct timespec* b)
{
    struct timespec result = {a->tv_sec + b->tv_sec, b->tv_nsec + b->tv_nsec};
    if(result.tv_nsec >= 1000000000)
    {
        result.tv_nsec -= 1000000000;
        ++result.tv_sec;
    }
    return result;
}

//Convert the milliseconds to timespec.
ts.tv_sec = milliseconds / 1000;
ts.tv_nsec = (milliseconds - (ts.tv_sec * 1000)) * 1000000;

//Convert the current time(timeval) to timespec.
timeval_to_timespec(&now, &spec_now);

ts = add_timespec(&ts, &spec_now); //add the milliseconds to the current time.

我想知道是否有更好的方法来完成上述操作。我宁愿不使用我的替代代码,但以前的代码似乎不太安全,而且我不喜欢模数。

想法?

【问题讨论】:

    标签: c++ c datetime timeval timespec


    【解决方案1】:

    您的第一种方法实际上是合理的,只是您在常量上犯了一些错字和错误。

    这个方法怎么样:

    ts.tv_sec = now.tv_sec + milliseconds / 1000;
    ts.tv_nsec = now.tv_usec * 1000 // 1000 ns per us, not a million!
                 + (milliseconds % 1000) * 1000000 // a million ns per ms.
    ts.tv_sec += ts.tv_nsec / 1000000000;
    ts.tv_nsec %= 1000000000;
    

    第二次加法没有溢出 32 位 int 的危险,因为 now.tv_usec * 1000 不超过 999,999,000,(milliseconds % 1000) * 1000000 不超过 999,000,000,所以总和最多为 1,998,999,000(以及秒数最后两行携带的总是0或1)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-11
      • 1970-01-01
      • 2014-09-30
      • 1970-01-01
      相关资源
      最近更新 更多