使用C ++中的put_time获得毫秒级的当前时间

问题描述 投票:3回答:1

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

std::time_t t = std::time(nullptr);
std::time(&t);
std::cout << std::put_time(std::localtime(&t), "%X,");

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

或者在C ++程序中有几种方法来获得毫秒级的系统时间?

c++ chrono
1个回答
4
投票

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

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

// a class to support using different chrono clocks and formats + milliseconds
template<class Clock = std::chrono::system_clock>
class log_watch {
public:
    using clock_type = Clock;
    // default format: "%Y-%m-%dT%H:%M:%S.<milliseconds>"
    log_watch(const std::string& format = "%FT%T.") : m_format(format) {}

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

private:
    std::string m_format;
};

template<class Clock>
std::ostream& operator<<(std::ostream& os, const log_watch<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);

    // get duration since epoch
    auto dur = time_point.time_since_epoch();

    // convert duration to milliseconds since epoch
    auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(dur).count();

    // output
    return os << std::put_time(std::localtime(&t), lw.m_format.c_str())
              << std::setfill('0') 
              << std::setw(3) 
              << ms % 1000;
}

int main() {
    log_watch def; // using the default clock and format
    log_watch<std::chrono::high_resolution_clock> hr("%X,");

    std::cout << def << "\n";
    std::cout << hr << "\n";
}
© www.soinside.com 2019 - 2024. All rights reserved.