c++ - 获得绝对时间的更好方法?

标签 c++ c datetime timeval timespec

目前我正在尝试获取与 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.

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

想法?

最佳答案

你的第一种方法实际上是合理的,除了你在常量上有一些错别字和错误。

这种方法怎么样:

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)。

关于c++ - 获得绝对时间的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28550750/

相关文章:

c++ - 使用相同的 udp 套接字进行异步接收/发送

C++ OpenCV imdecode 慢

c++ - 如何在模板类型中强制执行静态成员初始化?或者如何获取从模板类型派生的所有类的数量?

c - 当在同一文件中定义其调用函数时如何在 C 中模拟函数?

c - P线程和信号

c++ - clang 错误 : c++/4. 8/bits/STL_iterator_base_types.h:227:29: 错误: 'iterator_category' 中没有名为 'std::iterator_traits<unsigned long>' 的类型

c - 求给定字符串中数字的总和

php - 将非常规字符串转换为 mysql 日期时间?

python - 按在 Pandas 中开始和结束的日期范围扩展行

python将日期时间格式的字符串转换为秒