C++ 11实际系统时间,以毫秒为单位

zig*_*ggy 7 c++ time date c++11 c++-chrono

我有一个问题,用毫秒来获得实际的系统时间.我发现的唯一一个好方法是Windows.h,但我不能使用它.我应该用std::chrono.我怎样才能做到这一点?

我花了很多时间试图谷歌它,但我发现只有第二精度的例子.

我想要得到这样的字符串:

[2014-11-25 22:15:38:449]
Run Code Online (Sandbox Code Playgroud)

bam*_*s53 9

使用此答案中的代码:

#include <chrono>
#include <ctime>
#include <iostream>

template <typename Duration>
void print_time(tm t, Duration fraction) {
    using namespace std::chrono;
    std::printf("[%04u-%02u-%02u %02u:%02u:%02u.%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)));

    // VS2013's library has a bug which may require you to replace
    // "fraction / milliseconds(1)" with
    // "duration_cast<milliseconds>(fraction).count()"
}

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);

    print_time(*gmtime(&tt), tp);
    print_time(*localtime(&tt), tp);
}
Run Code Online (Sandbox Code Playgroud)

需要记住的一点是,定时器返回亚毫秒面额值的事实并不一定表明定时器具有亚毫秒级的分辨率.我认为Windows在VS2015中的实现可能最终得到修复,但到目前为止他们用来支持计时实现的计时器对操作系统timeBeginPeriod()设置很敏感,显示不同的分辨率,默认设置是16毫秒.

此外,上述代码假定UTC和您的本地时区都没有从时间偏移std::chrono::system_clock一小部分秒值.


使用Howard的日期函数来避免ctime的示例:http://coliru.stacked-crooked.com/a/98db840b238d3ce7

  • 如果你不想跋涉C API,你可以这样做:http://howardhinnant.github.io/date_algorithms.html#What%20can%20I%20do%20with%20that%20 <code>计时</代码>%20compatibility? (3认同)