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