C++ boost::posix_时间::微秒时钟以微秒分辨率增加到两倍秒

C++ boost::posix_时间::微秒时钟以微秒分辨率增加到两倍秒,c++,boost,posix,C++,Boost,Posix,我试图在互联网上找到答案。我需要以秒为单位的时间戳,分辨率为微秒 boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time(); // not really getting any further here double now_seconds = 0; // a value like 12345.123511, time since epoch in seconds with usec precis

我试图在互联网上找到答案。我需要以秒为单位的时间戳,分辨率为微秒

boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time();
// not really getting any further here
double now_seconds = 0; // a value like 12345.123511, time since epoch in seconds with usec precision
更新:


使用当前日期的开始作为历元就足够了,即24小时时间戳。

N.B.此答案提供了一种通用方法,允许使用任意历元,因为它是在更新之前编写的。”当需要相对于当前一天开始的时间戳时,s的答案是一个很好的简化


我不知道库中有一个函数可以完全满足您的要求,但借助文档,只需几行代码就可以实现您自己的功能

从表示历元的
ptime
中减去
ptime
,得到表示自历元以来经过的时间量的a。
time\u duration
类提供
total\u microseconds()
。适当缩放结果以获得秒数

代码示例
我解决了我的问题,至少它似乎工作正常(没有麻烦检查实际值,所以如果你想纠正我,请随意)


只是要小心你在事后如何计算这些双倍。以微秒为单位的历元变得如此之大,以至于只剩下少量的剩余位。首先,这意味着,如果取短时间跨度的差,可能会得到奇怪的持续时间,因为1/1000000.0不能精确地以二进制形式表示。例如,计算为a-b的2微秒持续时间,其中a和b为微秒,因为历元可能最终表示为2.125。@cnettel Good point。根据用例的不同,也许不同的纪元更合适。感谢您的回答,但我找到了一个更简单的解决方案。这只会给您给定一天开始以来的时间偏移量。@DanMašek感谢您的回答。我忘了写分区了。我需要一个24小时的时间戳,这样就好了。哦,好的:)顺便说一句,还有一个问题。
total_microseconds
的结果是一个
long
,因此您应该除以一个
double
常量以避免整数除法,即除以
1000000.0
。2) 变量名
usec
不再正确。。。好的,两个问题:)
#include <boost/date_time/local_time/local_time.hpp>
#include <boost/date_time/posix_time/ptime.hpp>
#include <boost/format.hpp>
#include <iostream>

double seconds_from_epoch(boost::posix_time::ptime const& t)
{
    boost::posix_time::ptime const EPOCH(boost::gregorian::date(1970,1,1));
    boost::posix_time::time_duration delta(t - EPOCH);
    return (delta.total_microseconds() / 1000000.0);
}


int main()
{
    boost::posix_time::ptime now(boost::posix_time::microsec_clock::local_time());
    std::cout << boost::format("%0.6f\n") % seconds_from_epoch(now);
    return 0;   
}
1497218065.918929
boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time();
double sec = now.time_of_day().total_microseconds()/1000000.0;