Skip to content

Instantly share code, notes, and snippets.

@buffyanamin
Last active December 29, 2021 08:49
Show Gist options
  • Save buffyanamin/2be2d7822c6e35fc2059754fba46cfe2 to your computer and use it in GitHub Desktop.
Save buffyanamin/2be2d7822c6e35fc2059754fba46cfe2 to your computer and use it in GitHub Desktop.
chrono helper(boost & std chrono inter-convertion)
#include <boost/chrono.hpp>
#include <chrono>
// from https://github.com/boostorg/chrono/issues/41#issuecomment-538932927
namespace sc = ::std::chrono;
namespace bc = ::boost::chrono;
namespace chrono_helper {
// std::is_same_v<to_std_ratio_t<boost::ratio<N,D>>, std::ratio<N,D>>
// if and only if N, D are coprime and D is positive
template<typename Ratio>
using to_std_ratio_t = std::ratio<Ratio::num, Ratio::den>;
// std::is_same_v<to_boost_ratio_t<std::ratio<N,D>>, boost::ratio<N,D>>
// if and only if N, D are coprime and D is positive
template<typename Ratio>
using to_boost_ratio_t = boost::ratio<Ratio::num, Ratio::den>;
template<typename Rep, typename Period> inline constexpr
sc::duration<Rep, to_std_ratio_t<Period>>
to_std_chrono(const bc::duration<Rep, Period> &d)
{
return sc::duration<Rep, to_std_ratio_t<Period>>
(d.count());
}
template<typename Rep, typename Period> inline constexpr
sc::time_point<sc::system_clock,
sc::duration<Rep, to_std_ratio_t<Period>>>
to_std_chrono(const bc::time_point<bc::system_clock,
bc::duration<Rep, Period>> &t)
{
// Assuming same epoch
return sc::time_point<sc::system_clock,
sc::duration<Rep, to_std_ratio_t<Period>>>
(to_std_chrono(t.time_since_epoch()));
}
template<typename Rep, typename Period> inline constexpr
bc::duration<Rep, to_boost_ratio_t<Period>>
to_boost_chrono(const sc::duration<Rep, Period> &d)
{
return bc::duration<Rep, to_boost_ratio_t<Period>>
(d.count());
}
template<typename Rep, typename Period> static constexpr
bc::time_point<bc::system_clock,
bc::duration<Rep, to_boost_ratio_t<Period>>>
to_boost_chrono(const sc::time_point<sc::system_clock,
sc::duration<Rep, Period>> &t)
{
// Assuming same epoch
return bc::time_point<bc::system_clock,
bc::duration<Rep, to_boost_ratio_t<Period>>>
(to_boost_chrono(t.time_since_epoch()));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment