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

时间:2015-02-16 21:34:53

标签: c++ c datetime timeval timespec

目前,我正试图获得与pthread_mutex_timedlock一起使用的绝对时间。我知道我需要将timevalgettimeofday添加到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.

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

想法?

1 个答案:

答案 0 :(得分: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)。

相关问题