Get chrono seconds in a float

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

The appeal 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 conversion examples.

How to get duration like int milli and float seconds from <chrono>?

C ++ chrono - duration as float or long long

timing in a certain way

Chrono Timer does not translate seconds properly

+5
source share
1 answer

Accordingly: http://en.cppreference.com/w/cpp/chrono/duration the default coefficient for the second parameter of the template 1:1 means seconds.

Other meanings are relationships regarding this. 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; 

Defined as seconds from which all other relationships are derived.

Regardless of which end - start units end - start defined when converting to std::ratio<1> , as in seconds.

If you need time in milliseconds, you can do:

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

And end - start should be converted in accordance with the new ratio.

+5
source

Source: https://habr.com/ru/post/1243328/


All Articles