// $Id: KrTime.C,v 1.2 2001/08/05 03:48:50 ben Exp $ #include #include #include #include KrTime::KrTime(double sec) { double intsec = floor(sec); _tv.tv_sec = (int) intsec; _tv.tv_usec = (int) floor((sec - intsec) * 1000000.0); } KrTime KrTime::now() { KrTime time; ::gettimeofday(&time._tv, NULL); return time; } std::ostream& operator << (std::ostream& ostr, const KrTime& t) { char str[30]; sprintf(str, "%ld.%06ld", t._tv.tv_sec, t._tv.tv_usec); return ostr << str; } // // Comparison operators // bool operator == (const KrTime& a, const KrTime& b) { return a._tv.tv_sec == b._tv.tv_sec && a._tv.tv_usec == b._tv.tv_usec; } bool operator != (const KrTime& a, const KrTime& b) { return a._tv.tv_sec != b._tv.tv_sec || a._tv.tv_usec != b._tv.tv_usec; } bool operator < (const KrTime& a, const KrTime& b) { return a._tv.tv_sec == b._tv.tv_sec ? a._tv.tv_usec < b._tv.tv_usec : a._tv.tv_sec < b._tv.tv_sec; } bool operator <= (const KrTime& a, const KrTime& b) { return a._tv.tv_sec == b._tv.tv_sec ? a._tv.tv_usec <= b._tv.tv_usec : a._tv.tv_sec <= b._tv.tv_sec; } bool operator > (const KrTime& a, const KrTime& b) { return a._tv.tv_sec == b._tv.tv_sec ? a._tv.tv_usec > b._tv.tv_usec : a._tv.tv_sec > b._tv.tv_sec; } bool operator >= (const KrTime& a, const KrTime& b) { return a._tv.tv_sec == b._tv.tv_sec ? a._tv.tv_usec >= b._tv.tv_usec : a._tv.tv_sec >= b._tv.tv_sec; } // // Arithmetic operators // KrTime operator + (const KrTime& a, const KrTime& b) { int usec = a._tv.tv_usec + b._tv.tv_usec; return KrTime(a._tv.tv_sec + b._tv.tv_sec + usec / 1000000, usec % 1000000); } KrTime operator - (const KrTime& a, const KrTime& b) { int usec = a._tv.tv_usec - b._tv.tv_usec; return KrTime(a._tv.tv_sec - b._tv.tv_sec - (usec < 0), (usec < 0) ? usec + 1000000 : usec); } KrTime& KrTime::operator += (const KrTime& t) { _tv.tv_usec += t._tv.tv_usec; _tv.tv_sec += t._tv.tv_sec + (_tv.tv_usec / 1000000); _tv.tv_usec %= 1000000; return *this; } KrTime& KrTime::operator -= (const KrTime& t) { _tv.tv_usec -= t._tv.tv_usec; _tv.tv_sec -= t._tv.tv_sec; if (_tv.tv_usec < 0) { _tv.tv_sec--; _tv.tv_usec += 1000000; } return *this; }