OpenSDN source code
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
time_util.h
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
3  */
4 
5 #ifndef BASE_TIME_UTIL_H__
6 #define BASE_TIME_UTIL_H__
7 
8 #include <sstream>
9 
10 #include <boost/date_time/posix_time/posix_time.hpp>
11 #include <boost/date_time/posix_time/posix_time_types.hpp>
12 /* timestamp - returns usec since epoch */
13 static inline uint64_t UTCTimestampUsec() {
14  struct timespec ts;
15  if (clock_gettime(CLOCK_REALTIME, &ts) != 0) {
16  assert(0);
17  }
18 
19  return ts.tv_sec * 1000000 + ts.tv_nsec/1000;
20 }
21 
22 /* timestamp - returns seconds since epoch */
23 static inline time_t UTCTimestamp() {
24  return time(NULL);
25 }
26 
27 // Monotonically increasing timer starting from an arbitrary value
28 // 10x more efficient than UTCTimestampUsec
29 static inline uint64_t ClockMonotonicUsec() {
30  struct timespec ts;
31  if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {
32  assert(0);
33  }
34 
35  return ts.tv_sec * 1000000 + ts.tv_nsec / 1000;
36 }
37 
38 static inline boost::posix_time::ptime UTCUsecToPTime(uint64_t tusec) {
39  typedef boost::posix_time::time_duration::sec_type sec_type;
40  typedef boost::posix_time::time_duration::fractional_seconds_type frac_type;
41 
42  int64_t tps = boost::posix_time::time_duration::ticks_per_second();
43  sec_type seconds = static_cast<sec_type>(tusec / 1000000);
44  frac_type frac_seconds =
45  static_cast<frac_type>(tps / 1000000 * (tusec % 1000000));
46 
47  boost::posix_time::ptime pt(
48  boost::gregorian::date(1970, 1, 1),
49  boost::posix_time::time_duration(0, 0, seconds, frac_seconds));
50 
51  return pt;
52 }
53 
54 static inline std::string UTCUsecToString(uint64_t tstamp) {
55  if (tstamp == 0)
56  return "";
57  std::stringstream ss;
58  ss << UTCUsecToPTime(tstamp);
59  return ss.str();
60 }
61 
62 static inline const std::string duration_usecs_to_string(const uint64_t usecs) {
63  std::ostringstream os;
64  boost::posix_time::time_duration duration;
65 
66  duration = boost::posix_time::microseconds(usecs);
67  os << duration;
68  return os.str();
69 }
70 
71 #endif // BASE_TIME_UTIL_H__
static boost::posix_time::ptime UTCUsecToPTime(uint64_t tusec)
Definition: time_util.h:38
static const std::string duration_usecs_to_string(const uint64_t usecs)
Definition: time_util.h:62
static time_t UTCTimestamp()
Definition: time_util.h:23
static uint64_t UTCTimestampUsec()
Definition: time_util.h:13
static uint64_t ClockMonotonicUsec()
Definition: time_util.h:29
static std::string UTCUsecToString(uint64_t tstamp)
Definition: time_util.h:54