Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ chrono - get duration as float or long long

Tags:

c++

chrono

I have a duration

typedef std::chrono::high_resolution_clock Clock;
Clock::time_point       beginTime;
Clock::time_point       endTime;
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - beginTime);

And I get duration in std::chrono::milliseconds. But I need duration as float or long long. How to do that?

like image 385
Narek Avatar asked Jul 10 '14 21:07

Narek


1 Answers

From the documentation

template<
    class Rep, 
    class Period = std::ratio<1> 
> class 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 constant representing the number of seconds from one tick to the next.

And:

count returns the count of ticks

So a duration stores a number of ticks of a specified period of time, and count will return that number using the underlying representation type. So if the duration's representation is long long, and the period is std::milli, then .count() will return a long long equal to the number of milliseconds represented by the duration.


In general you should avoid using weak types like float or long long to represent a duration. Instead you should stick with 'rich' types, such as std::chrono::milliseconds or an appropriate specialization of std::chrono::duration. These types aid correct usage and readability, and help prevent mistakes via type checking.

  • Underspecified / overly general:
    – void increase_speed(double);
    – Object obj; … obj.draw();
    – Rectangle(int,int,int,int);

  • Better: – void increase_speed(Speed);
    – Shape& s; … s.draw();
    – Rectangle(Point top_left, Point bottom_right);
    – Rectangle(Point top_left, Box_hw b);

— slide 18 from Bjarne's talk


std::chrono is "a consistent subset of a physical quantities library that handles only units of time and only those units of time with exponents equal to 0 and 1."

If you need to work with quantities of time you should take advantage of this library, or one that provides more complete unit systems, such as boost::units.

There are rare occasions where quantities must be degraded to weakly typed values. For example, when one must use an API that requires such types. Otherwise it should be avoided.

like image 173
bames53 Avatar answered Sep 27 '22 15:09

bames53