Raven Core  3.0.0
P2P Digital Currency
utiltime.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Copyright (c) 2017-2019 The Raven Core developers
4 // Distributed under the MIT software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 
7 #if defined(HAVE_CONFIG_H)
8 #include "config/raven-config.h"
9 #endif
10 
11 #include "utiltime.h"
12 
13 #include <atomic>
14 
15 #include <boost/date_time/posix_time/posix_time.hpp>
16 #include <boost/thread.hpp>
17 
18 static std::atomic<int64_t> nMockTime(0);
19 
20 int64_t GetTime()
21 {
22  int64_t mocktime = nMockTime.load(std::memory_order_relaxed);
23  if (mocktime) return mocktime;
24 
25  time_t now = time(nullptr);
26  assert(now > 0);
27  return now;
28 }
29 
30 void SetMockTime(int64_t nMockTimeIn)
31 {
32  nMockTime.store(nMockTimeIn, std::memory_order_relaxed);
33 }
34 
35 int64_t GetMockTime()
36 {
37  return nMockTime.load(std::memory_order_relaxed);
38 }
39 
40 int64_t GetTimeMillis()
41 {
42  int64_t now = (boost::posix_time::microsec_clock::universal_time() -
43  boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
44  assert(now > 0);
45  return now;
46 }
47 
48 int64_t GetTimeMicros()
49 {
50  int64_t now = (boost::posix_time::microsec_clock::universal_time() -
51  boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_microseconds();
52  assert(now > 0);
53  return now;
54 }
55 
57 {
58  return GetTimeMicros()/1000000;
59 }
60 
61 void MilliSleep(int64_t n)
62 {
63 
69 #if defined(HAVE_WORKING_BOOST_SLEEP_FOR)
70  boost::this_thread::sleep_for(boost::chrono::milliseconds(n));
71 #elif defined(HAVE_WORKING_BOOST_SLEEP)
72  boost::this_thread::sleep(boost::posix_time::milliseconds(n));
73 #else
74 //should never get here
75 #error missing boost sleep implementation
76 #endif
77 }
78 
79 std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime)
80 {
81  static std::locale classic(std::locale::classic());
82  // std::locale takes ownership of the pointer
83  std::locale loc(classic, new boost::posix_time::time_facet(pszFormat));
84  std::stringstream ss;
85  ss.imbue(loc);
86  ss << boost::posix_time::from_time_t(nTime);
87  return ss.str();
88 }
void MilliSleep(int64_t n)
Definition: utiltime.cpp:61
std::string DateTimeStrFormat(const char *pszFormat, int64_t nTime)
Definition: utiltime.cpp:79
void SetMockTime(int64_t nMockTimeIn)
Definition: utiltime.cpp:30
int64_t GetTimeMicros()
Definition: utiltime.cpp:48
int64_t GetSystemTimeInSeconds()
Definition: utiltime.cpp:56
int64_t GetTimeMillis()
Definition: utiltime.cpp:40
int64_t GetTime()
GetTimeMicros() and GetTimeMillis() both return the system time, but in different units...
Definition: utiltime.cpp:20
int64_t GetMockTime()
Definition: utiltime.cpp:35