jeudi 25 août 2016

How to convert a std::chrono::duration

I am finding std::chrono somewhat confusing and obstructive. I want to use real-valued milliseconds and end up with values like 0.7 or 6.45 or 13.3 that I can treat as double values.

I really just want to start from two time_point values and return the elapsed time between them as a double. How? This does not work:

using std;
using std::chrono;
high_resolution_clock::time_point t1( high_resolution_clock::now() );
// spend some time doing something...
high_resolution_clock::time_point t2( high_resolution_clock::now() );
const duration<double,milli> elapsedTime( t2 - t1 );
const double timeAsDouble( static_cast<double>( elapsedTime ) ); // no conversion available :-(
// go on to use or return timeAsDouble;

IMPORTANT CONSTRAINT: I specifically do not want to use values of type std::chrono::duration<double,std::milli>. Why not? Because I will immediately square the values I want to work with. When I square a double, I know it is a generic type, meaning that it is taking care of the number only, and not the units. So I have to explicitly take care of the units myself (e.g. by being clear about it in the variable name, even though this is prone to slip-ups).

But if I wanted to square a std::chrono::duration<double,std::milli>, I would open a can of worms either with regard to the units or to code clarity. In any case, no * operator is defined for multiplying this class by itself, so the second line in the example below avoids questions about its units and type by simply not compiling at all:

auto timeSpan( duration<double,std::milli>( 0.8 ) );
auto spanSquared( timeSpan*timeSpan );    // ???

So what is the easy way to turn what looks like it should be a double... into a double?

Aucun commentaire:

Enregistrer un commentaire