Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::chrono & Boost.Units

I'm working on a software design in which I'd like to leverage Boost.Units. Some of the units I'd like to use represent time, however, I'm inclined to use the C++11 std::chrono units for those since they're standard.

I'm wondering if there's any clean integration between Boost.Units and chrono or whether I have to resort to writing my own converters and lose type safety by just copying scalar values between the types.

Are there any best practices for this issue?

like image 676
user1714423 Avatar asked Oct 16 '13 20:10

user1714423


People also ask

What is STD Chrono in C ++?

> class 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.

What is Chrono High_resolution_clock?

Defined in header <chrono> class high_resolution_clock; (since C++11) Class std::chrono::high_resolution_clock represents the clock with the smallest tick period provided by the implementation. It may be an alias of std::chrono::system_clock or std::chrono::steady_clock, or a third, independent clock.

What does std :: Chrono :: System_clock :: now return?

std::chrono::system_clock::now Returns a time point representing with the current point in time.

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

std::chrono::duration_cast Converts the value of dtn into some other duration type, taking into account differences in their periods. The function does not use implicit conversions.


1 Answers

If you just want to convert a std::chrono duration to a boost time quantity you can use the following template function:

using time_quantity = boost::units::quantity<si::time, double>;

template<class _Period1, class _Type>
time_quantity toBoostTime( chrono::duration<_Type, _Period1> in)
{
  return time_quantity::from_value(double(in.count()) * double(_Period1::num) / double(_Period1::den) );
}

One thing to note is that the returned time_quantity will always be in seconds and the storage type will be of type double. If any of those two are a problem, the template can be adapted.

Example:

namespace bu = boost::units;
namespace sc = std::chrono;
using time_quantity_ms = bu::quantity<decltype(bu::si::milli * bu::si::second), int32_t>;

std::cout << "Test 1: " << toBoostTime(sc::seconds(10)) << std::endl;
std::cout << "Test 2: " << toBoostTime(sc::milliseconds(10)) << std::endl;
std::cout << "Test 3: " << static_cast<time_quantity_ms>(toBoostTime(sc::milliseconds(10))) << std::endl;

/* OUTPUT */
Test 1: 10 s
Test 2: 0.01 s
Test 3: 10 ms
like image 81
CJCombrink Avatar answered Oct 16 '22 14:10

CJCombrink