Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrono - The difference between two points in time in milliseconds?

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 a unsigned int, and not a float and then multiply by 1000?

like image 433
waas1919 Avatar asked Jul 27 '15 15:07

waas1919


People also ask

What is std :: Chrono :: duration?

Class template std::chrono::duration represents a time interval. It consists of a count of ticks of type Rep and a tick period, where the tick period is a compile-time rational fraction representing the time in seconds from one tick to the next. The only data stored in a duration is a tick count of type Rep .

What is std :: Chrono :: seconds?

std::chrono::secondsInstantiation of duration to represent seconds.


2 Answers

std::chrono::duration has two template parameters, the second being exactly the unit of measure. You can invoke std::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:

auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(foo - now); 

To get the actual number of milliseconds, use duration::count:

auto ms = milliseconds.count(); 

Its return type is duration::rep, which for standard duration types like std::chrono::milliseconds is a signed integer of unspecified size.

like image 122
lisyarus Avatar answered Sep 28 '22 14:09

lisyarus


chrono::duration_cast<chrono::milliseconds>(end_time - start_time).count() 
like image 39
zoska Avatar answered Sep 28 '22 13:09

zoska