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