time.hxx 1.8 KB

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