gpt4 book ai didi

c++ - boost::date_time (boost-145) 使用带有微秒计算的 64 位 uint,没有截断

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:41:48 25 4
gpt4 key购买 nike

我正在使用 date_time 来抽象掉平台特性。我需要生成一个 64 位微秒分辨率 uint64_t,它将用于序列化。我不明白下面出了什么问题。

#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/cstdint.hpp>
#include <iostream>

using namespace boost::posix_time;
using boost::uint64_t;

ptime UNIX_EPOCH(boost::gregorian::date(1970,1,1));

int main() {
ptime current_time = microsec_clock::universal_time();

std::cout << "original time: "<< current_time << std::endl;

long microsec_since_epoch = ((current_time -UNIX_EPOCH).total_microseconds());

ptime output_ptime = UNIX_EPOCH + microseconds(microsec_since_epoch);
std::cout << "Deserialized time : " << output_ptime << std::endl;

std::cout << "Microsecond output: " << microsec_since_epoch << std::endl;

std::cout << "Microsecond to second arithmetic: "
<< microsec_since_epoch/(10*10*10*10*10*10) << std::endl;

std::cout << "Microsecond to tiume_duration, back to microsecond : " <<
microseconds(microsec_since_epoch).total_microseconds() << std::endl;


return 0;
}

这是我得到的输出。

original time: 2010-Dec-17 09:52:06.737123
Deserialized time : 1970-Jan-16 03:10:41.577454
Microsecond output: 1292579526737123
Microsecond to second arithmetic: 1292579526
Microsecond to tiume_duration, back to microsecond : 1307441577454

当我切换到使用 total_seconds() 和 +seconds(..) 时,问题消失了——即,输入更改为:

2010-Dec-15 18:26:22.606978
2010-Dec-15 18:26:22

date_time 声称内部使用 64 位类型,2^64÷ (10^6×3600×24×365) ~= 584942 甚至 2^60÷ (10 ^6×3600×24×365) ~= 36558.

维基百科的开场白是关于 Posix 时间的

Unix time, or POSIX time, is a system for describing points in time, defined as the number of seconds elapsed since midnight Coordinated Universal Time (UTC) of January 1, 1970

为什么 40 年后仍会发生如此大规模的截断?

如何使用 boost::date_time 以微秒分辨率使用完整的 64 位空间?

--edit1 回应hans--

帖子已更改以反射(reflect) duration.total_microseconds() 部分的整数输出。注意 1292576572566904÷(10^6×3600×24×365) ~= 40.98 年。 seconds 的输出尚未更新。

--edit2--在“反序列化”步骤之前将微秒缩小到秒,也很有效。这种方法解决了我的问题,我在创建时只需要微秒分辨率,而在反序列化时我可以没有它。

我仍然想知道问题的内容和原因。

最佳答案

这似乎是 microseconds() 无法处理如此大的微秒输入的问题。以下代码片段修复了此问题:

#define MICROSEC 1000000

uint64_t sec_epoch = microsec_since_epoch / MICROSEC;
uint64_t mod_micro_epoch= microsec_since_epoch % MICROSEC;

ptime new_method = UNIX_EPOCH + seconds(sec_epoch) + microseconds(mod_micro_epoch);

std::cout << "Deserialization with new method: " << new_method << std::endl;

关于c++ - boost::date_time (boost-145) 使用带有微秒计算的 64 位 uint,没有截断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4453586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com