00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022 #include "timer.h"
00023
00024 #include <time.h>
00025 #include <sys/time.h>
00026
00027 #ifdef _WIN32
00028 #include <windows.h>
00029 #endif
00030
00031 namespace utils
00032 {
00033
00034 Timer::Timer(unsigned int ms, bool createActive)
00035 {
00036 active = createActive;
00037 interval = ms;
00038 lastpulse = getTimeInMillisec();
00039 }
00040
00041 void Timer::sleep()
00042 {
00043 if (!active) return;
00044 uint64_t now = getTimeInMillisec();
00045 if (now - lastpulse >= interval) return;
00046 #ifndef _WIN32
00047 struct timespec req;
00048 req.tv_sec = 0;
00049 req.tv_nsec = (interval - (now - lastpulse)) * (1000 * 1000);
00050 nanosleep(&req, 0);
00051 #else
00052 Sleep(interval - (now - lastpulse));
00053 #endif
00054 }
00055
00056 int Timer::poll()
00057 {
00058 int elapsed = 0;
00059 if (active)
00060 {
00061 uint64_t now = getTimeInMillisec();
00062 if (now > lastpulse)
00063 {
00064 elapsed = (now - lastpulse) / interval;
00065 lastpulse += interval * elapsed;
00066 }
00067 else
00068 {
00069
00070
00071 lastpulse = now;
00072 }
00073 };
00074 return elapsed;
00075 }
00076
00077 void Timer::start()
00078 {
00079 active = true;
00080 lastpulse = getTimeInMillisec();
00081 }
00082
00083 void Timer::stop()
00084 {
00085 active = false;
00086 }
00087
00088 void Timer::changeInterval(unsigned int newinterval)
00089 {
00090 interval = newinterval;
00091 }
00092
00093 uint64_t Timer::getTimeInMillisec()
00094 {
00095 uint64_t timeInMillisec;
00096 timeval time;
00097
00098 gettimeofday(&time, 0);
00099 timeInMillisec = (uint64_t)time.tv_sec * 1000 + time.tv_usec / 1000;
00100 return timeInMillisec;
00101 }
00102
00103 }