c++ - Persisting std::chrono time_point instances -
what correct way persist std::chrono time_point instances , read them instance of same type?
typedef std::chrono::time_point<std::chrono::high_resolution_clock> time_point_t; time_point_t tp = std::chrono::high_resolution_clock::now(); serializer.write(tp); . . . time_point_t another_tp; serializer.read(another_tp);
the calls write/read, assume instance of type time_point_t, can somehow converted byte representation, can written or read disk or socket etc.
a possible solution suggested alf follows:
std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now(); //generate pod write disk unsigned long long ns0 = t0.time_since_epoch().count(); //read pod disk , attempt instantiate time_point std::chrono::high_resolution_clock::duration d(ns0) std::chrono::high_resolution_clock::time_point t1(d); unsigned long long ns1 = t1.time_since_epoch().count(); if ((t0 != t1) || (ns0 != ns1)) { std::cout << "error time points don't match!\n"; }
note: above code has bug final instantiated time point not match original.
in case of of old style time_t, 1 typically writes entire entity disk based on sizeof , reads same way - in short equivalent new std::chrono types?
the time_point
constructor takes duration
, , can duration
member time_since_epoch
. question reduces serialize duration
value. , duration
has constructor takes number of ticks, , member function count
produces number of ticks.
all googling std::chrono::time_point
, looking @ cppreference documentation google landed me on.
it's idea read documentation.
addendum: example.
#include <chrono> #include <iostream> #include <typeinfo> using namespace std; auto main() -> int { using clock = chrono::high_resolution_clock; using time_point = clock::time_point; using duration = clock::duration; time_point const t0 = clock::now(); //generate pod write disk duration::rep const ns0 = t0.time_since_epoch().count(); //read pod disk , attempt instantiate time_point duration const d(ns0); time_point const t1(d); cout << "basic number type " << typeid( ns0 ).name() << "." << endl; if( t0 != t1 ) { cout << "error time points don't match!" << endl; } else { cout << "reconstituted time ok." << endl; } }
with visual c++ 12.0 reported basic type __int64
, i.e. long long
, while g++ 4.8.2 in windows reported type x
, presumably means same.
with both compilers reconstituted time identical original.
addendum: noted dina in comments, of c++14 c++ standard doesn't specify epoch, , make work across machines or different clocks it's necessary add additional steps normalize epoch serialized data, e.g. , naturally posix time, i.e. time since since 00:00:00 coordinated universal time (utc), thursday, 1 january 1970.
Comments
Post a Comment