00001 #ifndef _REAL_TIME_H
00002 #define _REAL_TIME_H
00003
00004 #include <string>
00005 #include <sys/time.h>
00006 #include <stdexcept>
00007 #include <cassert>
00008
00009 namespace osl
00010 {
00011 namespace misc
00012 {
00013 struct NoMoreTime : std::runtime_error
00014 {
00015 NoMoreTime() : std::runtime_error("time limit over")
00016 {
00017 }
00018 };
00019
00020 class RealTime
00021 {
00022 timeval start, end;
00023 public:
00027 explicit RealTime (long timeleft)
00028 {
00029 gettimeofday (&start, 0);
00030 end = start;
00031 end.tv_sec += timeleft;
00032 }
00033
00034 explicit RealTime (timeval timeleft)
00035 {
00036 gettimeofday (&start, 0);
00037 end = start;
00038 end.tv_sec += timeleft.tv_sec;
00039 end.tv_usec += timeleft.tv_usec;
00040 }
00041
00042 bool isInvalid() const {
00043 return end.tv_sec - start.tv_sec < 0;
00044 }
00045
00046 bool
00047 timeLeft () const
00048 {
00049 return getTimeLeftInSeconds() > 0;
00050 }
00051
00052 timeval getTimeLeft () const
00053 {
00054 timeval now;
00055 gettimeofday (&now , 0);
00056 return diff(end, now);
00057 }
00058 int getTimeLeftInSeconds () const
00059 {
00060 return getTimeLeft().tv_sec;
00061 }
00062 double getTimeLeftInDouble () const
00063 {
00064 return toDouble(getTimeLeft());
00065 }
00066 timeval getConsumed () const
00067 {
00068 timeval now;
00069 gettimeofday (&now , 0);
00070 return diff(now, start);
00071 }
00072 double getConsumedInDouble() const
00073 {
00074 return toDouble(getConsumed());
00075 }
00076
00077 const std::string getEnd() const;
00078
00079 static timeval diff(timeval l, timeval r)
00080 {
00081 timeval ret;
00082 ret.tv_sec = l.tv_sec - r.tv_sec;
00083 ret.tv_usec = l.tv_usec - r.tv_usec;
00084
00085 if (ret.tv_usec < 0)
00086 {
00087 --ret.tv_sec;
00088 ret.tv_usec += 1000000;
00089 }
00090
00091 return ret;
00092 }
00093 static double toDouble(timeval t) {
00094 return t.tv_sec + t.tv_usec/1000000.0;
00095 }
00096 };
00097 }
00098 }
00099
00100
00101 #endif //_REAL_TIME
00102
00103
00104
00105