round.hpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // boost/chrono/round.hpp ------------------------------------------------------------//
  2. // (C) Copyright Howard Hinnant
  3. // Copyright 2011 Vicente J. Botet Escriba
  4. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. // See http://www.boost.org/libs/chrono for documentation.
  7. #ifndef BOOST_CHRONO_ROUND_HPP
  8. #define BOOST_CHRONO_ROUND_HPP
  9. #include <boost/chrono/duration.hpp>
  10. #include <boost/chrono/duration.hpp>
  11. //#include <boost/chrono/typeof/boost/chrono/chrono.hpp>
  12. namespace boost
  13. {
  14. namespace chrono
  15. {
  16. /**
  17. * rounds to nearest, to even on tie
  18. */
  19. template <class To, class Rep, class Period>
  20. To round(const duration<Rep, Period>& d)
  21. {
  22. typedef typename common_type<To, duration<Rep, Period> >::type result_type;
  23. result_type diff0;
  24. result_type diff1;
  25. To t0 = duration_cast<To>(d);
  26. To t1 = t0;
  27. if (t0>d) {
  28. --t1;
  29. diff0 = t0 - d;
  30. diff1 = d - t1;
  31. } else {
  32. ++t1;
  33. diff0 = d - t0;
  34. diff1 = t1 - d;
  35. }
  36. if (diff0 == diff1)
  37. {
  38. if (t0.count() & 1)
  39. return t1;
  40. return t0;
  41. }
  42. else if (diff0 < diff1)
  43. return t0;
  44. return t1;
  45. }
  46. } // namespace chrono
  47. } // namespace boost
  48. #endif