Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get chrono seconds in float

In the example at http://en.cppreference.com/w/cpp/chrono the seconds value is obtained in a double. This is the behavior I want. However, this appears to rely on the implicit assumption that the time point subtraction yields a value that represents seconds. I can not find anything that explains why a duration yields floating point seconds when no time units are actually specified. Without using auto at all, can someone show how to explicitly obtain a time unit such as seconds in a floating point type, or point me to documentation or explanation as to why the aforementioned conversion represents seconds?

The conversion in question is essentially:

std::chrono::time_point<std::chrono::system_clock> start = std::chrono::system_clock::now();
std::chrono::time_point<std::chrono::system_clock> end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end-start; // why does this represent seconds as opposed to some other time unit?
double secondsInDouble = elapsed_seconds.count();

See the following posts for examples of the conversion.

How to get duration, as int milli's and float seconds from <chrono>?

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

getting chrono time in specific way

Chrono Timer Not Converting Seconds Properly

like image 290
taz Avatar asked Feb 18 '16 16:02

taz


People also ask

What is Chrono duration?

(since C++11) 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.

Which Chrono function allows us to convert a clock duration from one unit to the other?

std::chrono::duration_cast.


1 Answers

According to this: http://en.cppreference.com/w/cpp/chrono/duration the default ratio for the second template parameter is 1:1 meaning seconds.

Other values are ratios relative to that. For example the ratio for std::chrono::milliseconds is 1:1000 http://en.cppreference.com/w/cpp/numeric/ratio/ratio

So this statement:

std::chrono::duration<double> elapsed_seconds = end-start;

is equivalent to:

std::chrono::duration<double, std::ratio<1>> elapsed_seconds = end-start;

Which is defined to be seconds from which all other ratios are derived.

Whatever units end - start are defined in get converted to std::ratio<1> as in seconds.

If you wanted the time in milliseconds you could do:

std::chrono::duration<double, std::ratio<1, 1000>> elapsed_milliseconds = end-start;

And end - start should be converted according to the new ratio.

like image 151
Galik Avatar answered Oct 08 '22 01:10

Galik