在C ++中使用put_time以毫秒精度获取当前时间

pan*_*des 3 c++ c++-chrono

我正在使用以下代码来获取C ++中的当前时间。

std::time_t t = std::time(nullptr);
std::time(&t);
std::cout << std::put_time(std::localtime(&t), "%X,");
Run Code Online (Sandbox Code Playgroud)

但是,这给了我时间HH :: MM :: SS。但是对于我的应用程序,我还想包含毫秒数。反正有使用std :: put_time获得类似HH :: MM :: SS :: msecs的东西吗?

或者在C ++程序中有几种方法可以使系统时间达到毫秒精度?

Ted*_*gmo 5

这是一个使用某些C ++ 11 <chrono>功能的示例。如果可以使用C ++ 20,请查看新<chrono>功能以获取更多帮助,或查看Howard Hinnants Date库。

#include <chrono>
#include <cstdint>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <string>
#include <type_traits>

// A C++11 constexpr function template for counting decimals needed for
// selected precision.
template<std::size_t V, std::size_t C = 0,
         typename std::enable_if<(V < 10), int>::type = 0>
constexpr std::size_t log10ish() {
    return C;
}

template<std::size_t V, std::size_t C = 0,
         typename std::enable_if<(V >= 10), int>::type = 0>
constexpr std::size_t log10ish() {
    return log10ish<V / 10, C + 1>();
}

// A class to support using different precisions, chrono clocks and formats
template<class Precision = std::chrono::seconds,
         class Clock = std::chrono::system_clock>
class log_watch {
public:
    // some convenience typedefs and "decimal_width" for sub second precisions
    using precision_type = Precision;
    using ratio_type = typename precision_type::period;
    using clock_type = Clock;
    static constexpr auto decimal_width = log10ish<ratio_type{}.den>();

    static_assert(ratio_type{}.num <= ratio_type{}.den,
                  "Only second or sub second precision supported");
    static_assert(ratio_type{}.num == 1, "Unsupported precision parameter");

    // default format: "%Y-%m-%dT%H:%M:%S"
    log_watch(const std::string& format = "%FT%T") : m_format(format) {}

    template<class P, class C>
    friend std::ostream& operator<<(std::ostream&, const log_watch<P, C>&);

private:
    std::string m_format;
};

template<class Precision, class Clock>
std::ostream& operator<<(std::ostream& os, const log_watch<Precision, Clock>& lw) {
    // get current system clock
    auto time_point = Clock::now();

    // extract std::time_t from time_point
    std::time_t t = Clock::to_time_t(time_point);

    // output the part supported by std::tm
    os << std::put_time(std::localtime(&t), lw.m_format.c_str());

    // only involve chrono duration calc for displaying sub second precisions
    if(lw.decimal_width) { // if constexpr( ... in C++17
        // get duration since epoch
        auto dur = time_point.time_since_epoch();

        // extract the sub second part from the duration since epoch
        auto ss =
            std::chrono::duration_cast<Precision>(dur) % std::chrono::seconds{1};

        // output the sub second part
        os << std::setfill('0') << std::setw(lw.decimal_width) << ss.count();
    }

    return os;
}

int main() {
    // default precision, clock and format
    log_watch<> def_cp; // <= C++14
    // log_watch def;   // >= C++17

    // alt. precision using alternative formats
    log_watch<std::chrono::milliseconds> milli("%X,");
    log_watch<std::chrono::microseconds> micro("%FT%T.");
    // alt. precision and clock - only supported if the clock is an alias for
    // system_clock
    log_watch<std::chrono::nanoseconds,
              std::chrono::high_resolution_clock> nano("%FT%T.");

    std::cout << "def_cp: " << def_cp << "\n";
    std::cout << "milli : " << milli << "\n";
    std::cout << "micro : " << micro << "\n";
    std::cout << "nano  : " << nano << "\n";
}
Run Code Online (Sandbox Code Playgroud)

输出示例:

def_cp: 2019-11-21T13:44:07
milli : 13:44:07,871
micro : 2019-11-21T13:44:07.871939
nano  : 2019-11-21T13:44:07.871986585
Run Code Online (Sandbox Code Playgroud)