Get an unsigned int milliseconds out of chrono::duration

北城以北 提交于 2020-08-01 06:23:55

问题


For a winapi wrapper I want to use chrono for a duration given to the call. The code example:

bool setTimer(std::chrono::duration<std::chrono::milliseconds> duration)
{
    unsigned int dwDuration = Do some chrono magic here

    SetTimer(m_hWnd,1,dwDuration,0);
}

dwDuration has to be in milliseconds.

First question: How do to the magic.

Second question: Is the parameter declaration okay?


回答1:


The name of the type is std::chrono::milliseconds, and it has a member function count() that returns the number of those milliseconds:

bool setTimer(std::chrono::milliseconds duration)
{
    unsigned int dwDuration = duration.count();
    return std::cout << "dwDuration = " << dwDuration << '\n';
}

online demo: http://coliru.stacked-crooked.com/a/03f29d41e9bd260c

If you want to be ultra-pedantic, the return type of count() is std::chrono::milliseconds::rep

If you want to deal with fractional milliseconds, then the type would be std::chrono::duration<double, std::milli> (and the return type of count() is then double)




回答2:


You can use the following code:

auto now = chrono::high_resolution_clock::now();

auto timeMillis = chrono::duration_cast<chrono::milliseconds>(now.time_since_epoch()).count();


来源:https://stackoverflow.com/questions/20785687/get-an-unsigned-int-milliseconds-out-of-chronoduration

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!