6

現在の時刻からエポック秒と小数秒を提供する単純なタイムスタンプシステムを作成しようとしています。私はブーストライブラリを使用していて、次のようなものがあります:

const boost::posix_time::ptime epoch(boost::gregorian::date(1970, 1, 1));
boost::posix_time::ptime time() {
    boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();
    return now;
}
boost::posix_time::time_duration dur = (time() - epoch);

次に、次の要素を使用してエポック値を抽出します。

dur.total_seconds();
dur.fractional_seconds();

具体的には、これは適切なUNIX時間を返しますか?そうでない場合、それを修正する方法に関する提案はありますか?ありがとう。

4

1 に答える 1

6

はい、それはうまくいくはずですが、確かに、常に実験的な証拠があります:

#include <iostream>
#include <time.h>
#include <boost/date_time.hpp>
namespace bpt = boost::posix_time;
namespace bg = boost::gregorian;
int main()
{
    bpt::time_duration dur = bpt::microsec_clock::universal_time()
                           - bpt::ptime(bg::date(1970, 1, 1));
    timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);
    std::cout << std::setfill('0')
              << " boost: " << dur.total_seconds() << '.' << std::setw(6)
                            << dur.fractional_seconds() << '\n'
              << " ctime: " << time(NULL) << '\n'
              << " posix: " << ts.tv_sec << '.' << std::setw(9)
                            << ts.tv_nsec << '\n';
}

私は得る

Linux/gcc

 boost: 1361502964.664746
 ctime: 1361502964
 posix: 1361502964.664818326

サン/サンスタジオ

 boost: 1361503762.775609
 ctime: 1361503762
 posix: 1361503762.775661600

AIX/XLC

 boost: 1361503891.342930
 ctime: 1361503891
 posix: 1361503891.342946000

さらには Windows/Visual Studio

 boost: 1361504377.084231
 ctime: 1361504377

から何秒経過したかについては、全員が一致しているようです。date(1970,1,1)

于 2013-02-22T03:23:16.740 に答える