Update to latest libsecp256k1
[bitcoinplatinum.git] / src / utiltime.cpp
blob510f540b1d51b61c1f9d9447a7042e47c2475e24
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 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.
6 #if defined(HAVE_CONFIG_H)
7 #include "config/bitcoin-config.h"
8 #endif
10 #include "utiltime.h"
12 #include <atomic>
14 #include <boost/date_time/posix_time/posix_time.hpp>
15 #include <boost/thread.hpp>
17 static std::atomic<int64_t> nMockTime(0); //!< For unit testing
19 int64_t GetTime()
21 int64_t mocktime = nMockTime.load(std::memory_order_relaxed);
22 if (mocktime) return mocktime;
24 time_t now = time(NULL);
25 assert(now > 0);
26 return now;
29 void SetMockTime(int64_t nMockTimeIn)
31 nMockTime.store(nMockTimeIn, std::memory_order_relaxed);
34 int64_t GetTimeMillis()
36 int64_t now = (boost::posix_time::microsec_clock::universal_time() -
37 boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
38 assert(now > 0);
39 return now;
42 int64_t GetTimeMicros()
44 int64_t now = (boost::posix_time::microsec_clock::universal_time() -
45 boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_microseconds();
46 assert(now > 0);
47 return now;
50 int64_t GetSystemTimeInSeconds()
52 return GetTimeMicros()/1000000;
55 /** Return a time useful for the debug log */
56 int64_t GetLogTimeMicros()
58 int64_t mocktime = nMockTime.load(std::memory_order_relaxed);
59 if (mocktime) return mocktime*1000000;
61 return GetTimeMicros();
64 void MilliSleep(int64_t n)
67 /**
68 * Boost's sleep_for was uninterruptible when backed by nanosleep from 1.50
69 * until fixed in 1.52. Use the deprecated sleep method for the broken case.
70 * See: https://svn.boost.org/trac/boost/ticket/7238
72 #if defined(HAVE_WORKING_BOOST_SLEEP_FOR)
73 boost::this_thread::sleep_for(boost::chrono::milliseconds(n));
74 #elif defined(HAVE_WORKING_BOOST_SLEEP)
75 boost::this_thread::sleep(boost::posix_time::milliseconds(n));
76 #else
77 //should never get here
78 #error missing boost sleep implementation
79 #endif
82 std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime)
84 static std::locale classic(std::locale::classic());
85 // std::locale takes ownership of the pointer
86 std::locale loc(classic, new boost::posix_time::time_facet(pszFormat));
87 std::stringstream ss;
88 ss.imbue(loc);
89 ss << boost::posix_time::from_time_t(nTime);
90 return ss.str();