Last active
April 23, 2019 06:12
-
-
Save abhi1010/f6356685a1b8d97f51f24c1e9e163486 to your computer and use it in GitHub Desktop.
print std::chrono::duration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
edit mode | history | |
10 hours | |
36000 seconds | |
60000 intervals of 0.600000 (3/5) seconds each |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <chrono> | |
#include <string> | |
namespace utility | |
{ | |
namespace chrono | |
{ | |
constexpr inline const char* units( std::chrono::nanoseconds ) noexcept { return "nanoseconds" ; } | |
constexpr inline const char* units( std::chrono::microseconds ) noexcept { return "microseconds" ; } | |
constexpr inline const char* units( std::chrono::milliseconds ) noexcept { return "milliseconds" ; } | |
constexpr inline const char* units( std::chrono::seconds ) noexcept { return "seconds" ; } | |
constexpr inline const char* units( std::chrono::minutes ) noexcept { return "minutes" ; } | |
constexpr inline const char* units( std::chrono::hours ) noexcept { return "hours" ; } | |
template < std::intmax_t A, std::intmax_t B > struct gcd | |
{ static constexpr std::intmax_t value = gcd<B,A%B>::value ; }; | |
template < std::intmax_t A > struct gcd<A,0> | |
{ static constexpr std::intmax_t value = A ; }; | |
template < typename R, std::intmax_t N, std::intmax_t D > | |
std::string units( std::chrono::duration< R, std::ratio<N,D> > ) | |
{ | |
constexpr auto NN = N / gcd<N,D>::value ; | |
constexpr auto DD = D / gcd<N,D>::value ; | |
return "intervals of " + std::to_string( double(N) / D ) + | |
" (" + std::to_string(NN) + '/' + std::to_string(DD) + ") seconds each" ; | |
} | |
} | |
} | |
template < typename R, std::intmax_t N, std::intmax_t D > | |
std::ostream& operator<< ( std::ostream& stm, std::chrono::duration< R, std::ratio<N,D> > d ) | |
{ return stm << d.count() << ' ' << utility::chrono::units( decltype(d){} ) ; } | |
int main() | |
{ | |
std::chrono::hours duration_hrs(10) ; | |
std::cout << duration_hrs << '\n' | |
<< std::chrono::duration_cast<std::chrono::seconds>(duration_hrs) << '\n' | |
<< std::chrono::duration< double, std::ratio<36,60> >(duration_hrs) << '\n' ; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment