yaodav
yaodav

Reputation: 1256

how to create time stamp with microsecond

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]

Upvotes: 3

Views: 1359

Answers (2)

Howard Hinnant
Howard Hinnant

Reputation: 218700

template <typename Rep, typename Period>
void
print_time(tm t, std::chrono::duration<Rep, Period> fraction)
{
    using namespace std::chrono;
    auto ms = duration_cast<milliseconds>(fraction);
    fraction -= ms;
    auto us = duration_cast<microseconds>(fraction);
    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>(ms / milliseconds(1)),
        static_cast<unsigned>(us / microseconds(1)));
}
  • The change I made to your parameter keeps it from being overly generic and accepting something that is not a chrono::duration.

  • To get the number of milliseconds out of fraction (and assuming fraction is non-negative), just duration_cast<milliseconds>(fraction).

  • Now you need to subtract the milliseconds obtained in the previous step out of fraction, lest they will come back to haunt you in the next step.

  • To get the number of microseconds out of fraction (and assuming fraction is non-negative), just duration_cast<microseconds>(fraction).

If you wanted to go further and get the nanoseconds out of fraction, you would need to first subtract the microseconds part out before proceeding.

Upvotes: 3

Silerus
Silerus

Reputation: 36

You are losing accuracy on this line:
tp -= duration_cast<seconds>(tp);
Get data in microseconds at once, and better in nanoseconds, and then re-read them in the desired format.

Upvotes: 0

Related Questions