1 // file : examples/cxx/parser/performance/time.hxx 2 // copyright : not copyrighted - public domain 3 4 #ifndef TIME_HXX 5 #define TIME_HXX 6 7 #include <iosfwd> // std::ostream& 8 9 namespace os 10 { 11 class time 12 { 13 public: 14 class failed {}; 15 16 // Create a time object representing the current time. 17 // 18 time (); 19 time(unsigned long long nsec)20 time (unsigned long long nsec) 21 { 22 sec_ = static_cast<unsigned long> (nsec / 1000000000ULL); 23 nsec_ = static_cast<unsigned long> (nsec % 1000000000ULL); 24 } 25 time(unsigned long sec,unsigned long nsec)26 time (unsigned long sec, unsigned long nsec) 27 { 28 sec_ = sec; 29 nsec_ = nsec; 30 } 31 32 public: 33 unsigned long sec() const34 sec () const 35 { 36 return sec_; 37 } 38 39 unsigned long nsec() const40 nsec () const 41 { 42 return nsec_; 43 } 44 45 public: 46 class overflow {}; 47 class underflow {}; 48 49 time operator +=(time const & b)50 operator+= (time const& b) 51 { 52 unsigned long long tmp = 0ULL + nsec_ + b.nsec_; 53 54 sec_ += static_cast<unsigned long> (b.sec_ + tmp / 1000000000ULL); 55 nsec_ = static_cast<unsigned long> (tmp % 1000000000ULL); 56 57 return *this; 58 } 59 60 time operator -=(time const & b)61 operator-= (time const& b) 62 { 63 if (*this < b) 64 throw underflow (); 65 66 sec_ -= b.sec_; 67 68 if (nsec_ < b.nsec_) 69 { 70 --sec_; 71 nsec_ += 1000000000ULL - b.nsec_; 72 } 73 else 74 nsec_ -= b.nsec_; 75 76 return *this; 77 } 78 79 friend time operator +(time const & a,time const & b)80 operator+ (time const& a, time const& b) 81 { 82 time r (a); 83 r += b; 84 return r; 85 } 86 87 friend time operator -(time const & a,time const & b)88 operator- (time const& a, time const& b) 89 { 90 time r (a); 91 r -= b; 92 return r; 93 } 94 95 friend bool operator <(time const & a,time const & b)96 operator < (time const& a, time const& b) 97 { 98 return (a.sec_ < b.sec_) || (a.sec_ == b.sec_ && a.nsec_ < b.nsec_); 99 } 100 101 private: 102 unsigned long sec_; 103 unsigned long nsec_; 104 }; 105 106 std::ostream& 107 operator<< (std::ostream&, time const&); 108 } 109 110 #endif // TIME_HXX 111