I'm trying to generate a timestamp with a resolution of a microsecond. I tried using this answer Extract year/month/day etc. from std::chrono::time_point in C++ and also this one: C++11 actual system time with milliseconds but I'm not sure that doing it right:
template <typename Duration>
void print_time(tm t, Duration fraction) {
using namespace std::chrono;
std::printf("[%04u-%02u-%02u %02u:%02u:%02u.%03u.%03u]\n", t.tm_year + 1900,
t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec,
static_cast<unsigned>(fraction / milliseconds(1)),
static_cast<unsigned>(fraction / microseconds(1)));
}
int main() {
using namespace std;
using namespace std::chrono;
system_clock::time_point now = system_clock::now();
system_clock::duration tp = now.time_since_epoch();
tp -= duration_cast<seconds>(tp);
time_t tt = system_clock::to_time_t(now);
cout << tp.count() <<endl;
print_time(*gmtime(&tt), tp);
print_time(*localtime(&tt), tp);
and the output for this code is :
324760155 [2019-09-15 10:09:13.324.324760] [2019-09-15 10:09:13.324.324760]
```std::chrono::time_point
Name the number of microseconds, we can divide them by the number of microseconds per hour, get hours / in a minute - get minutes / in a second. You just need to remember to subtract the result already obtained.