fork(3) download
  1. #include <chrono>
  2. #include <iostream>
  3. #include <tuple>
  4.  
  5. using day_t = std::chrono::duration<long long, std::ratio<3600 * 24>>;
  6.  
  7. template<typename> struct duration_traits {};
  8. #define DURATION_TRAITS(Duration, Singular, Plural) \
  9. template<> struct duration_traits<Duration> { \
  10. constexpr static const char* singular = Singular; \
  11. constexpr static const char* plural = Plural; \
  12. }
  13.  
  14. DURATION_TRAITS(std::chrono::milliseconds, "millisecond", "milliseconds");
  15. DURATION_TRAITS(std::chrono::seconds, "second", "seconds");
  16. DURATION_TRAITS(std::chrono::minutes, "minute", "minutes");
  17. DURATION_TRAITS(std::chrono::hours, "hour", "hours");
  18. DURATION_TRAITS(day_t, "day", "days");
  19.  
  20. using divisions = std::tuple<std::chrono::milliseconds,
  21. std::chrono::seconds,
  22. std::chrono::minutes,
  23. std::chrono::hours,
  24. day_t>;
  25.  
  26. namespace detail {
  27. template<typename...> struct print_duration_impl_ {};
  28.  
  29. template<typename Head, typename... Tail>
  30. struct print_duration_impl_<Head, Tail...> {
  31. template <typename Duration>
  32. static bool print(std::ostream& os, Duration& dur) {
  33. const auto started_printing = print_duration_impl_<Tail...>::print(os, dur);
  34.  
  35. const auto n = std::chrono::duration_cast<Head>(dur);
  36. const auto count = n.count();
  37.  
  38. if (count == 0) {
  39. return started_printing;
  40. }
  41.  
  42. if (started_printing) {
  43. os << ' ';
  44. }
  45.  
  46. using traits = duration_traits<Head>;
  47. os << count << ' ' << (count == 1 ? traits::singular : traits::plural);
  48. dur -= n;
  49.  
  50. return true;
  51. }
  52. };
  53.  
  54. template<> struct print_duration_impl_<> {
  55. template <typename Duration>
  56. static bool print(std::ostream& os, Duration& dur) {
  57. return false;
  58. }
  59. };
  60.  
  61. template<typename...> struct print_duration {};
  62.  
  63. template<typename... Args>
  64. struct print_duration<std::tuple<Args...>> {
  65. template<typename Duration>
  66. static void print(std::ostream& os, Duration dur) {
  67. print_duration_impl_<Args...>::print(os, dur);
  68. }
  69. };
  70. }
  71.  
  72. template<typename Rep, typename Period>
  73. std::ostream& operator<<(std::ostream& os, const std::chrono::duration<Rep, Period>& dur) {
  74. detail::print_duration<divisions>::print(os, dur);
  75. return os;
  76. }
  77.  
  78. #include <thread>
  79.  
  80. int main() {
  81. auto start = std::chrono::system_clock::now();
  82. std::this_thread::sleep_for(std::chrono::milliseconds(1492));
  83. auto end = std::chrono::system_clock::now();
  84.  
  85. std::cout << (end - start) << std::endl;
  86.  
  87. return 0;
  88. }
Success #stdin #stdout 0s 3300KB
stdin
Standard input is empty
stdout
1 second 492 milliseconds