获得绝对时间的更好方法
Better way to get absolute time?
当前我正在尝试获得与pthread_mutex_timedlock
一起使用的绝对时间。我知道我需要将timeval
从gettimeofday
添加到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
不超过999999 000,(milliseconds % 1000) * 1000000
不超过999000000,所以总和最多为1998999 000(最后两行的秒数总是0或1)。
相关文章:
- 初始化具有非默认构造函数的std::数组项的更好方法
- Protobuf中重复字段的问题.使用重复字段进行序列化/反序列化的更好方法是什么?
- 编写按初始值循环的循环的更好方法是什么
- 用 c++ 为游戏制作"bullet"的更好方法?
- 在CMakeLists中包含目录的更好方法.txt
- 将QDomDocument数据用作文本的更好方法
- C++ - 创建具有相同字符的特定大小的以 null 结尾的 c 样式字符串的更好方法
- 在 sqlite3 中批量插入的更好方法C++
- 设计许多单例代码结构的更好方法
- 使用继承的类模板避免公共成员不可见和源代码膨胀/重复的更好方法
- 在初始化列表中初始化数组的更好方法
- 将对象从一个 std::d eque 移动到另一个的更好方法
- 请告诉我在巴泽尔拥有多平台工作空间的更好方法
- 构造具有大量数据的对象的更好方法(C++)
- 从2D矢量中找出最小尺寸的向量元素的更好方法
- 在C++中创建不可变对象的更好方法
- 在构造函数中组织初始值设定项列表的更好方法
- std::copy with return values - 防止"expression: string iterators incompatible"的更好方法?
- 删除数组成员的更好方法是什么?
- 在C 中操作数据的更好方法是什么