io_ex5.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // io_ex1.cpp ----------------------------------------------------------//
  2. // Copyright 2010 Howard Hinnant
  3. // Copyright 2010 Vicente J. Botet Escriba
  4. // Distributed under the Boost Software License, Version 1.0.
  5. // See http://www.boost.org/LICENSE_1_0.txt
  6. /*
  7. This code was adapted by Vicente J. Botet Escriba from Hinnant's html documentation.
  8. Many thanks to Howard for making his code available under the Boost license.
  9. */
  10. #include <boost/chrono/chrono_io.hpp>
  11. #include <ostream>
  12. #include <iostream>
  13. // format duration as [-]d/hh::mm::ss.cc
  14. template <class CharT, class Traits, class Rep, class Period>
  15. std::basic_ostream<CharT, Traits>&
  16. display(std::basic_ostream<CharT, Traits>& os,
  17. boost::chrono::duration<Rep, Period> d)
  18. {
  19. using std::cout;
  20. using namespace boost;
  21. using namespace boost::chrono;
  22. typedef duration<long long, ratio<86400> > days;
  23. typedef duration<long long, centi> centiseconds;
  24. // if negative, print negative sign and negate
  25. if (d < duration<Rep, Period>(0))
  26. {
  27. d = -d;
  28. os << '-';
  29. }
  30. // round d to nearest centiseconds, to even on tie
  31. centiseconds cs = duration_cast<centiseconds>(d);
  32. if (d - cs > milliseconds(5)
  33. || (d - cs == milliseconds(5) && cs.count() & 1))
  34. ++cs;
  35. // separate seconds from centiseconds
  36. seconds s = duration_cast<seconds>(cs);
  37. cs -= s;
  38. // separate minutes from seconds
  39. minutes m = duration_cast<minutes>(s);
  40. s -= m;
  41. // separate hours from minutes
  42. hours h = duration_cast<hours>(m);
  43. m -= h;
  44. // separate days from hours
  45. days dy = duration_cast<days>(h);
  46. h -= dy;
  47. // print d/hh:mm:ss.cc
  48. os << dy.count() << '/';
  49. if (h < hours(10))
  50. os << '0';
  51. os << h.count() << ':';
  52. if (m < minutes(10))
  53. os << '0';
  54. os << m.count() << ':';
  55. if (s < seconds(10))
  56. os << '0';
  57. os << s.count() << '.';
  58. if (cs < centiseconds(10))
  59. os << '0';
  60. os << cs.count();
  61. return os;
  62. }
  63. int main()
  64. {
  65. using std::cout;
  66. using namespace boost;
  67. using namespace boost::chrono;
  68. #ifdef BOOST_CHRONO_HAS_CLOCK_STEADY
  69. display(cout, steady_clock::now().time_since_epoch()
  70. + duration<long, mega>(1)) << '\n';
  71. #endif
  72. display(cout, -milliseconds(6)) << '\n';
  73. display(cout, duration<long, mega>(1)) << '\n';
  74. display(cout, -duration<long, mega>(1)) << '\n';
  75. }
  76. //~ 12/06:03:22.95
  77. //~ -0/00:00:00.01
  78. //~ 11/13:46:40.00
  79. //~ -11/13:46:40.00