00001 #ifndef TIMESTAMP_H 00002 #define TIMESTAMP_H 00003 00004 #include <sys/time.h> 00005 #include <sstream> 00006 #include <NMSTL/serial> 00007 00008 using namespace std; 00009 00010 class Timestamp : public timeval 00011 { 00012 private: 00013 static const long MILLION = 1000000; 00014 00015 public: 00016 Timestamp() { 00017 tv_sec = 0; 00018 tv_usec = 0; 00019 } 00020 Timestamp(long sec, long usec) { 00021 tv_sec = sec; 00022 tv_usec = usec; 00023 } 00024 Timestamp(const timeval &t) { 00025 tv_sec = t.tv_sec; 00026 tv_usec = t.tv_usec; 00027 } 00028 00029 static Timestamp now() { 00030 timeval t; 00031 gettimeofday(&t, NULL); 00032 return Timestamp(t); 00033 } 00034 00035 Timestamp &operator+=(const Timestamp &rhs) { 00036 tv_sec += rhs.tv_sec; 00037 tv_usec += rhs.tv_usec; 00038 if (tv_usec >= MILLION) { 00039 tv_sec += 1; 00040 tv_usec -= MILLION; 00041 } 00042 return *this; 00043 } 00044 00045 Timestamp operator-(const Timestamp &rhs) const { 00046 long ret_sec = tv_sec - rhs.tv_sec; 00047 long ret_usec = tv_usec - rhs.tv_usec; 00048 if (ret_usec < 0) { 00049 ret_sec -= 1; 00050 ret_usec += MILLION; 00051 } 00052 return Timestamp(ret_sec, ret_usec); 00053 } 00054 00055 Timestamp &operator-=(const Timestamp &t) { 00056 tv_sec -= t.tv_sec; 00057 tv_usec -= t.tv_usec; 00058 if (tv_usec < 0) { 00059 tv_sec -= 1; 00060 tv_usec += MILLION; 00061 } 00062 return *this; 00063 } 00064 00065 bool operator==(const Timestamp &t) const { 00066 return ((tv_sec == t.tv_sec) && 00067 (tv_usec == t.tv_usec)); 00068 } 00069 00070 bool operator<(const Timestamp &t) const { 00071 return ((tv_sec < t.tv_sec) || 00072 ((tv_sec == t.tv_sec) && 00073 (tv_usec < t.tv_usec))); 00074 } 00075 00076 bool operator>(const Timestamp &t) const { 00077 return ((tv_sec > t.tv_sec) || 00078 ((tv_sec == t.tv_sec) && 00079 (tv_usec > t.tv_usec))); 00080 } 00081 00082 long long to_usecs() const { 00083 return tv_sec * 1000000LL + tv_usec; 00084 } 00085 00086 long long to_msecs() const { 00087 return to_usecs()/1000; 00088 } 00089 00090 timeval to_timeval() const { 00091 timeval t; 00092 t.tv_sec = tv_sec; 00093 t.tv_usec = tv_usec; 00094 return t; 00095 } 00096 00097 const string as_string() const { 00098 ostringstream oss; 00099 oss << "(" << tv_sec << ", " << tv_usec << ")"; 00100 return oss.str(); 00101 } 00102 #ifdef ENABLE_SERIALIZATION 00103 NMSTL_SIMPLY_SERIALIZABLE(Timestamp, << tv_sec << tv_usec); 00104 #endif 00105 00106 }; 00107 00108 #endif