How can I get (using the std::chrono
library) the difference between two points in time in milliseconds?
I could do that using this:
std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now();
std::chrono::time_point<std::chrono::system_clock> foo = now + std::chrono::milliseconds(100);
std::chrono::duration<float> difference = foo - now;
const int milliseconds = difference.count() * 1000;
How can I get this time in milliseconds, so I can use the duration as an unsigned int
, and not a float
and then multiply by 1000?
Best Answer
std::chrono::duration
has two template parameters, the second being exactly the unit of measure. You can invokestd::chrono::duration_cast
to cast from one duration type to another. Also, there is a predefined duration type for milliseconds:std::chrono::milliseconds
. Composing this together:To get the actual number of milliseconds, use
duration::count
:Its return type is
duration::rep
, which for standard duration types likestd::chrono::milliseconds
is a signed integer of unspecified size.