lundi 17 juin 2019

std::chrono time points, duration conversions, and fractional values

Say I time a task with the following:

auto t1 = std::chrono::high_resolution_clock::now();
// ...do work here...
auto t2 = std::chrono::high_resolution_clock::now();

The time that elapsed is:

auto elapsed = t2 - t1;

I'm a bit confused as to what units duration uses, and how to correctly convert it to seconds with fractional seconds.

If I do this:

std::cout << "count=" << elapsed.count() << std::endl;

...then I seem to get nanoseconds. But if I do this instead:

const double secs = std::chrono::duration<double>(elapsed).count();
std::cout << "count=" << secs << std::endl;

...then it looks like I get the seconds and fractional seconds I was hoping to work with.

While this code works with the compiler I'm using, I worry that because I'm not specifying the units I want during the conversion of the duration, what I've done is implementation-specific and may not work as expected with a different compiler. Is there a better or more explicit way to convert the duration to "seconds" (including the fractional part)?

Aucun commentaire:

Enregistrer un commentaire