C ++ 11实际系统时间(毫秒) [英] C++11 actual system time with milliseconds

查看:188
本文介绍了C ++ 11实际系统时间(毫秒)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've got a problem with getting actual system time with milliseconds. The only one good method I found is in Windows.h, but I can't use it. I'm supposed to use std::chrono. How can I do this?

我花了很多时间去google它,但我发现只有二次精度的例子。

I spent a lot of time trying to google it, but I found only second-precision examples.

我想得到这样的字符串:

I'm trying to get string like this:

[2014-11-25 22:15:38:449]


推荐答案

http://stackoverflow.com/a/15958113/365496\">此答案:

Using code from this answer:

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

需要记住的一件事是,定时器返回值亚毫秒的面额不一定表示定时器具有亚毫秒的分辨率。我认为VS2015中的Windows实现最终可能是固定的,但是他们已经用来回退他们的计时器实现到目前为止的计时器一直敏感于操作系统 timeBeginPeriod() 设置,显示不同的分辨率,设置是我想的16毫秒。

One thing to keep in mind is that the fact that the timer returns values of sub-millisecond denominations does not necessarily indicate that the timer has sub-millisecond resolution. I think Windows' implementation in VS2015 may finally be fixed, but the timer they've been using to back their chrono implementation so far has been sensitive to the OS timeBeginPeriod() setting, displaying varying resolution, and the default setting is I think 16 milliseconds.

上面的代码假设UTC和你的本地时区都不偏离 std :: chrono

Also the above code assumes that neither UTC nor your local timezone are offset from the epoch of std::chrono::system_clock by a fractional second value.

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

Example of using Howard's date functions to avoid ctime: http://coliru.stacked-crooked.com/a/98db840b238d3ce7

这篇关于C ++ 11实际系统时间(毫秒)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆