You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

utiltime.cpp 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2016 The Starwels developers
  3. // Distributed under the MIT software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #if defined(HAVE_CONFIG_H)
  6. #include "config/starwels-config.h"
  7. #endif
  8. #include "utiltime.h"
  9. #include <atomic>
  10. #include <boost/date_time/posix_time/posix_time.hpp>
  11. #include <boost/thread.hpp>
  12. static std::atomic<int64_t> nMockTime(0); //!< For unit testing
  13. int64_t GetTime()
  14. {
  15. int64_t mocktime = nMockTime.load(std::memory_order_relaxed);
  16. if (mocktime) return mocktime;
  17. time_t now = time(nullptr);
  18. assert(now > 0);
  19. return now;
  20. }
  21. void SetMockTime(int64_t nMockTimeIn)
  22. {
  23. nMockTime.store(nMockTimeIn, std::memory_order_relaxed);
  24. }
  25. int64_t GetMockTime()
  26. {
  27. return nMockTime.load(std::memory_order_relaxed);
  28. }
  29. int64_t GetTimeMillis()
  30. {
  31. int64_t now = (boost::posix_time::microsec_clock::universal_time() -
  32. boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
  33. assert(now > 0);
  34. return now;
  35. }
  36. int64_t GetTimeMicros()
  37. {
  38. int64_t now = (boost::posix_time::microsec_clock::universal_time() -
  39. boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_microseconds();
  40. assert(now > 0);
  41. return now;
  42. }
  43. int64_t GetSystemTimeInSeconds()
  44. {
  45. return GetTimeMicros()/1000000;
  46. }
  47. void MilliSleep(int64_t n)
  48. {
  49. /**
  50. * Boost's sleep_for was uninterruptible when backed by nanosleep from 1.50
  51. * until fixed in 1.52. Use the deprecated sleep method for the broken case.
  52. * See: https://svn.boost.org/trac/boost/ticket/7238
  53. */
  54. #if defined(HAVE_WORKING_BOOST_SLEEP_FOR)
  55. boost::this_thread::sleep_for(boost::chrono::milliseconds(n));
  56. #elif defined(HAVE_WORKING_BOOST_SLEEP)
  57. boost::this_thread::sleep(boost::posix_time::milliseconds(n));
  58. #else
  59. //should never get here
  60. #error missing boost sleep implementation
  61. #endif
  62. }
  63. std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime)
  64. {
  65. static std::locale classic(std::locale::classic());
  66. // std::locale takes ownership of the pointer
  67. std::locale loc(classic, new boost::posix_time::time_facet(pszFormat));
  68. std::stringstream ss;
  69. ss.imbue(loc);
  70. ss << boost::posix_time::from_time_t(nTime);
  71. return ss.str();
  72. }