Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an unsigned int milliseconds out of chrono::duration

Tags:

c++11

chrono

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?

like image 943
Martin Schlott Avatar asked Dec 26 '13 13:12

Martin Schlott


2 Answers

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)

like image 140
Cubbi Avatar answered Nov 03 '22 09:11

Cubbi


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();
like image 27
Ivan Mushketyk Avatar answered Nov 03 '22 10:11

Ivan Mushketyk