Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create time stamp with microsecond

Tags:

c++

c++-chrono

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]

like image 240
yaodav Avatar asked Mar 19 '26 17:03

yaodav


1 Answers

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.

like image 143
Howard Hinnant Avatar answered Mar 21 '26 07:03

Howard Hinnant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!