Line data Source code
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 41293698 : static inline uint64_t UTCTimestampUsec() { 14 : struct timespec ts; 15 41293698 : if (clock_gettime(CLOCK_REALTIME, &ts) != 0) { 16 374 : assert(0); 17 : } 18 : 19 41306795 : return ts.tv_sec * 1000000 + ts.tv_nsec/1000; 20 : } 21 : 22 : /* timestamp - returns seconds since epoch */ 23 3414617 : static inline time_t UTCTimestamp() { 24 3414617 : return time(NULL); 25 : } 26 : 27 : // Monotonically increasing timer starting from an arbitrary value 28 : // 10x more efficient than UTCTimestampUsec 29 190689 : static inline uint64_t ClockMonotonicUsec() { 30 : struct timespec ts; 31 190689 : if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) { 32 14 : assert(0); 33 : } 34 : 35 190740 : return ts.tv_sec * 1000000 + ts.tv_nsec / 1000; 36 : } 37 : 38 18031 : 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 18031 : int64_t tps = boost::posix_time::time_duration::ticks_per_second(); 43 18031 : sec_type seconds = static_cast<sec_type>(tusec / 1000000); 44 18031 : frac_type frac_seconds = 45 18031 : static_cast<frac_type>(tps / 1000000 * (tusec % 1000000)); 46 : 47 : boost::posix_time::ptime pt( 48 18024 : boost::gregorian::date(1970, 1, 1), 49 36051 : boost::posix_time::time_duration(0, 0, seconds, frac_seconds)); 50 : 51 17995 : return pt; 52 : } 53 : 54 23125 : static inline std::string UTCUsecToString(uint64_t tstamp) { 55 23125 : if (tstamp == 0) 56 17640 : return ""; 57 5489 : std::stringstream ss; 58 5489 : ss << UTCUsecToPTime(tstamp); 59 5489 : return ss.str(); 60 5489 : } 61 : 62 1379 : static inline const std::string duration_usecs_to_string(const uint64_t usecs) { 63 1379 : std::ostringstream os; 64 1379 : boost::posix_time::time_duration duration; 65 : 66 1379 : duration = boost::posix_time::microseconds(usecs); 67 1379 : os << duration; 68 2758 : return os.str(); 69 1379 : } 70 : 71 : #endif // BASE_TIME_UTIL_H__