11

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

Community
  • 1
  • 1
taz
  • 1,506
  • 3
  • 15
  • 26

1 Answers1

8

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.

Galik
  • 47,303
  • 4
  • 80
  • 117
  • I see the part I missed at the top of the reference: `tick period is a compile-time rational constant representing the number of seconds from one tick to the next.` So given the default ratio of 1:1, a duration period always represents one second. Thanks for bringing this to my attention. – taz Feb 18 '16 at 17:54
  • 4
    `std::ratio<1, 1000>` can be replaced with `std::milli`. – Artem Klevtsov Jun 20 '16 at 15:02