Get current time in milliseconds or HH: MM: SS: MMM format

I wrote a C ++ function to get the current time in a format HH:MM:SS. How to add milliseconds or nanoseconds, so I can have a format, for example HH:MM:SS:MMM? If this is not possible, a function that returns the current time in ms will also be good. Then I can calculate the relative time intervals between the two log points.

string get_time()
{
    time_t t = time(0);   // get time now
    struct tm * now = localtime(&t);
    std::stringstream sstm;
    sstm << (now->tm_hour) << ':' << (now->tm_min) << ':' << now->tm_sec;
    string s = sstm.str();
    return s;
}
+7
source share
2 answers

Instead of using time()(seconds from the era) try gettimeofday(). Gives you a structure that includes a microsecond field.

0
source

This is a portable method using the C++11chrono library :

#include <chrono>
#include <ctime>
#include <iomanip>
#include <sstream>
#include <string>

// ...

std::string time_in_HH_MM_SS_MMM()
{
    using namespace std::chrono;

    // get current time
    auto now = system_clock::now();

    // get number of milliseconds for the current second
    // (remainder after division into seconds)
    auto ms = duration_cast<milliseconds>(now.time_since_epoch()) % 1000;

    // convert to std::time_t in order to convert to std::tm (broken time)
    auto timer = system_clock::to_time_t(now);

    // convert to broken time
    std::tm bt = *std::localtime(&timer);

    std::ostringstream oss;

    oss << std::put_time(&bt, "%H:%M:%S"); // HH:MM:SS
    oss << '.' << std::setfill('0') << std::setw(3) << ms.count();

    return oss.str();
}
+14

Source: https://habr.com/ru/post/1547988/


All Articles