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.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2015 The Bitcoin Core 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/bitcoin-config.h"
  7. #endif
  8. #include "utiltime.h"
  9. #include <boost/date_time/posix_time/posix_time.hpp>
  10. #include <boost/thread.hpp>
  11. using namespace std;
  12. static int64_t nMockTime = 0; //!< For unit testing
  13. int64_t GetTime()
  14. {
  15. if (nMockTime) return nMockTime;
  16. time_t now = time(NULL);
  17. assert(now > 0);
  18. return now;
  19. }
  20. void SetMockTime(int64_t nMockTimeIn)
  21. {
  22. nMockTime = nMockTimeIn;
  23. }
  24. int64_t GetTimeMillis()
  25. {
  26. int64_t now = (boost::posix_time::microsec_clock::universal_time() -
  27. boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
  28. assert(now > 0);
  29. return now;
  30. }
  31. int64_t GetTimeMicros()
  32. {
  33. int64_t now = (boost::posix_time::microsec_clock::universal_time() -
  34. boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_microseconds();
  35. assert(now > 0);
  36. return now;
  37. }
  38. /** Return a time useful for the debug log */
  39. int64_t GetLogTimeMicros()
  40. {
  41. if (nMockTime) return nMockTime*1000000;
  42. return GetTimeMicros();
  43. }
  44. void MilliSleep(int64_t n)
  45. {
  46. /**
  47. * Boost's sleep_for was uninterruptable when backed by nanosleep from 1.50
  48. * until fixed in 1.52. Use the deprecated sleep method for the broken case.
  49. * See: https://svn.boost.org/trac/boost/ticket/7238
  50. */
  51. #if defined(HAVE_WORKING_BOOST_SLEEP_FOR)
  52. boost::this_thread::sleep_for(boost::chrono::milliseconds(n));
  53. #elif defined(HAVE_WORKING_BOOST_SLEEP)
  54. boost::this_thread::sleep(boost::posix_time::milliseconds(n));
  55. #else
  56. //should never get here
  57. #error missing boost sleep implementation
  58. #endif
  59. }
  60. std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime)
  61. {
  62. // std::locale takes ownership of the pointer
  63. std::locale loc(std::locale::classic(), new boost::posix_time::time_facet(pszFormat));
  64. std::stringstream ss;
  65. ss.imbue(loc);
  66. ss << boost::posix_time::from_time_t(nTime);
  67. return ss.str();
  68. }