You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. // timing.cpp
  2. //
  3. // Copyright (C) 2004-2020 MicroNeil Research Corporation.
  4. //
  5. // This software is released under the MIT license. See LICENSE.TXT.
  6. #include <ctime>
  7. #include <sys/time.h>
  8. #include <cerrno>
  9. // Platform Specific Includes //////////////////////////////////////////////////
  10. #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64)
  11. #include <windows.h>
  12. #endif
  13. #include "timing.hpp"
  14. namespace codedweller {
  15. ///////////////////////////////////////////////////////////////////////////////
  16. // class Sleeper - An object that remembers how long it is supposed to sleep.
  17. // This allows an application to create "standard" sleep timers. This also
  18. // helps keep sleeper values within range to avoid weird timing problems.
  19. ///////////////////////////////////////////////////////////////////////////////
  20. // Abstracted doRawSleep() function ////////////////////////////////////////////
  21. #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64)
  22. // In a WIN32 environment Sleep() is defined and it works in milliseconds so
  23. // we will use that for doRawSleep(). It's important to note that under normal
  24. // circumstances win32 Sleep() may be off by quite a bit (15ms or so) due to
  25. // how timing is done in the OS. There are ways around this, but they are
  26. // sometimes complex - so here I've left things basic. If more precise win32
  27. // timing is needed then this method can be recoded using a workaround that is
  28. // appropriate to the application.
  29. void Sleeper::doRawSleep(int x) {
  30. Sleep(x); // Use windows Sleep()
  31. }
  32. #else
  33. // If we are not in a win32 environment then we're likely on a posix/unix system
  34. // or at least we have the standard posix/unix time functions so we'll redefine
  35. // absSleep to use nanosleep();
  36. void Sleeper::doRawSleep(int x) {
  37. struct timespec sleeptime; // How much sleeping to do.
  38. struct timespec remaining; // How much sleeping remains.
  39. int result; // The latest result.
  40. remaining.tv_sec = x/1000; // Divide ms by 1000 to get secs.
  41. remaining.tv_nsec = (x%1000)*1000000; // Multiply the remaining msecs to get nsecs.
  42. do { // Just in case we get interruped...
  43. sleeptime.tv_sec = remaining.tv_sec; // Get our sleep time from the
  44. sleeptime.tv_nsec = remaining.tv_nsec; // remaining time.
  45. result = nanosleep(&sleeptime,&remaining); // Call nanosleep and get the remaining time.
  46. } while(0>result && EINTR==errno); // If we were interrupted sleep some more.
  47. }
  48. #endif
  49. Sleeper::Sleeper() // Constructed empty we set our
  50. :MillisecondsToSleep(0) { // sleep time to zero.
  51. }
  52. Sleeper::Sleeper(int x) { // Constructed with a value we
  53. setMillisecondsToSleep(x); // set the sleep time or throw.
  54. }
  55. int Sleeper::setMillisecondsToSleep(int x) { // Safe way to set the vlaue.
  56. if(x < MinimumSleeperTime ||
  57. x > MaximumSleeperTime) // If it's not a good time value
  58. throw BadSleeperValue(); // then throw the exception.
  59. MillisecondsToSleep = x; // If it is good - set it.
  60. return MillisecondsToSleep; // Return the set value.
  61. }
  62. int Sleeper::getMillisecondsToSleep() { // Safe way to get the value.
  63. return MillisecondsToSleep; // Send back the value.
  64. }
  65. void Sleeper::sleep() { // Here's where we snooze.
  66. if(MillisecondsToSleep > 0) { // If we have a good snooze
  67. doRawSleep(MillisecondsToSleep); // value then go to Sleep().
  68. } else { // If the value is not good
  69. throw BadSleeperValue(); // throw an exception.
  70. }
  71. }
  72. void Sleeper::sleep(int x) { // Reset the sleep time then sleep.
  73. setMillisecondsToSleep(x); // Set the sleep time.
  74. sleep(); // Sleep.
  75. }
  76. void Sleeper::operator()() { // Syntactic sugar - operator() on
  77. sleep(); // a sleeper calls sleep().
  78. }
  79. ///////////////////////////////////////////////////////////////////////////////
  80. // class PollTimer - An object to pause during polling processes where the
  81. // time between polls is expanded according to a Fibonacci sequence. This
  82. // allows self organizing automata to relax a bit when a particular process
  83. // is taking a long time so that the resources used in the polling process are
  84. // reduced if the system is under load - The idea is to prevent the polling
  85. // process from loading the system when there are many nodes poling, yet to
  86. // allow for a rapid response when there are few or when the answer we're
  87. // waiting for is ready quickly. We use a Fibonacci expansion because it is
  88. // a natural spiral.
  89. ///////////////////////////////////////////////////////////////////////////////
  90. PollTimer::PollTimer(int Nom, int Max) :
  91. NominalPollTime(MinimumSleeperTime),
  92. MaximumPollTime(MinimumSleeperTime) { // Construction requires a
  93. setNominalPollTime(Nom); // nominal delay to use and
  94. setMaximumPollTime(Max); // a maximum delay to allow.
  95. }
  96. int PollTimer::setNominalPollTime(int Nom) { // Set the Nominal Poll Time.
  97. if(Nom < MinimumSleeperTime || // Check the low and high
  98. Nom > MaximumSleeperTime) // limits and throw an
  99. throw BadPollTimerValue(); // exception if we need to.
  100. // If the value is good then
  101. NominalPollTime = Nom; // remember it.
  102. if(MaximumPollTime < NominalPollTime) // Make sure the Maximum poll
  103. MaximumPollTime = NominalPollTime; // time is >= the Nominal time.
  104. reset(); // Reset due to the change.
  105. return NominalPollTime; // Return the new value.
  106. }
  107. int PollTimer::setMaximumPollTime(int Max) { // Set the Maximum Poll Time.
  108. if(Max < MinimumSleeperTime || // Check the low and high
  109. Max > MaximumSleeperTime) // limits and throw an
  110. throw BadPollTimerValue(); // exception if we need to.
  111. // If the value is good then
  112. MaximumPollTime = Max; // remember it.
  113. if(MaximumPollTime < NominalPollTime) // Make sure the Maximum poll
  114. MaximumPollTime = NominalPollTime; // time is >= the Nominal time.
  115. reset(); // Reset due to the change.
  116. return MaximumPollTime; // Return the new value.
  117. }
  118. void PollTimer::reset() { // Reset the spiral.
  119. FibA = NominalPollTime; // Assume our starting event.
  120. FibB = 0; // Assume no other events.
  121. LimitReached=false; // Reset our limit watcher.
  122. }
  123. int PollTimer::pause() { // Pause between polls.
  124. int SleepThisTime = MaximumPollTime; // Assume we're at out limit for now.
  125. if(LimitReached) { // If actually are at our limit then
  126. mySleeper.sleep(SleepThisTime); // use the current value.
  127. } else { // If we are still expanding then
  128. SleepThisTime = FibA+FibB; // Calculate the time to use and
  129. if(SleepThisTime >= MaximumPollTime) { // check it against the limit. If
  130. SleepThisTime = MaximumPollTime; // we reached the limit, us that value
  131. LimitReached = true; // and set the flag.
  132. } else { // If we haven't reached the limit yet
  133. FibB=FibA; // then shift our events and remember
  134. FibA=SleepThisTime; // this one to build our spiral.
  135. }
  136. mySleeper.sleep(SleepThisTime); // Take a nap.
  137. } // Then FIRE THE MISSILES!
  138. return SleepThisTime; // Tell the caller how long we slept.
  139. }
  140. ///////////////////////////////////////////////////////////////////////////////
  141. // class Timer - This one acts much like a stop watch with millisecond
  142. // resolution. The time is based on wall-clock time using gettimeofday().
  143. ///////////////////////////////////////////////////////////////////////////////
  144. #ifdef WIN32
  145. // Here is the win32 version of getLocalRawClock()
  146. #define TimerIsUnixBased (false)
  147. msclock Timer::getLocalRawClock() const {
  148. FILETIME t; // We need a FILETIME structure.
  149. msclock c; // We need a place to calculate our value.
  150. GetSystemTimeAsFileTime(&t); // Grab the system time.
  151. c = (unsigned long long int) t.dwHighDateTime << 32LL; // Put full seconds into the high order bits.
  152. c |= t.dwLowDateTime; // Put 100ns ticks into the low order bits.
  153. c /= 10000; // Divide 100ns ticks by 10K to get ms.
  154. c -= EPOCH_DELTA_IN_MSEC; // Correct for the epoch difference.
  155. return c; // Return the result.
  156. }
  157. #else
  158. // Here is the unix/posix version of getLocalRawClock()
  159. #define TimerIsUnixBased (true)
  160. msclock Timer::getLocalRawClock() const {
  161. struct timeval t; // We need a timval structure.
  162. msclock c; // We need a place to calculate our value.
  163. gettimeofday(&t,NULL); // Grab the system time.
  164. c = t.tv_sec * 1000; // Put the full seconds in as milliseconds.
  165. c += t.tv_usec / 1000; // Add the microseconds as milliseconds.
  166. return c; // Return the milliseconds.
  167. }
  168. #endif
  169. Timer::Timer() { // Construct by resetting the
  170. start(); // clocks by using start();
  171. }
  172. Timer::Timer(msclock startt): // Construct a timer from a specific time.
  173. RunningFlag(true), // Set the running flag,
  174. StartTime(startt), // the start time and
  175. StopTime(startt) { // the stop time clock to startt.
  176. }
  177. void Timer::clear() { // Stop, zero elapsed, now.
  178. StartTime = StopTime = getLocalRawClock(); // Set the start and stop time
  179. RunningFlag = false; // to now. We are NOT running.
  180. }
  181. msclock Timer::start() { // (re) Start the timer at this moment.
  182. return start(getLocalRawClock()); // start() using the current raw clock.
  183. }
  184. msclock Timer::start(msclock startt) { // (re) Start a timer at startt.
  185. StartTime = StopTime = startt; // Set the start and end clocks.
  186. RunningFlag = true; // Set the running flag to true.
  187. return StartTime; // Return the start clock.
  188. }
  189. msclock Timer::getStartClock() { return StartTime; } // Return the start clock value.
  190. bool Timer::isRunning() { return RunningFlag; } // Return the running state.
  191. msclock Timer::getElapsedTime() const { // Return the elapsed timeofday -
  192. msclock AssumedStopTime; // We need to use a StopTime simulation.
  193. if(RunningFlag) { // If we are running we must get
  194. AssumedStopTime = getLocalRawClock(); // the current time (as if it were stop).
  195. } else { // If we are not running we use
  196. AssumedStopTime = StopTime; // the actual stop time.
  197. }
  198. msclock delta = AssumedStopTime - StartTime; // Calculate the difference.
  199. return delta; // That's our result.
  200. }
  201. msclock Timer::stop() { // Stop the timer.
  202. StopTime = getLocalRawClock(); // Grab the time and then stop
  203. RunningFlag=false; // the clock.
  204. return StopTime; // Return the time we stopped.
  205. }
  206. msclock Timer::getStopClock() { return StopTime; } // Return the stop clock value.
  207. double Timer::getElapsedSeconds() const { // Calculate the elapsed seconds.
  208. msclock e = getElapsedTime(); // Get the elapsed time in msecs.
  209. double secs = (double) e / 1000.0; // Calculate seconds from msecs.
  210. return secs;
  211. }
  212. bool Timer::isUnixBased() { return TimerIsUnixBased; } // Is this timer unix based?
  213. msclock Timer::toWindowsEpoch(msclock unixt) { // Convert a unix based msclock to win32 based.
  214. return (unixt + EPOCH_DELTA_IN_MSEC); // Going this way we add the epoch delta.
  215. }
  216. msclock Timer::toUnixEpoch(msclock win32t) { // Convert a win32 based msclock to a unix based.
  217. return (win32t - EPOCH_DELTA_IN_MSEC); // Going this way we subtract the epoch delta.
  218. }
  219. ///////////////////////////////////////////////////////////////////////////////
  220. // class Timeout - This one uses a Timer to establish a timeout value.
  221. ///////////////////////////////////////////////////////////////////////////////
  222. Timeout::Timeout(msclock duration):myDuration(duration) { } // Create, set the duration, start.
  223. msclock Timeout::setDuration(msclock duration) { // Set/Change the duration in milliseconds.
  224. myDuration = duration; // (re) Set the duration.
  225. return myDuration; // Return the current (new) duration.
  226. }
  227. msclock Timeout::getDuration() { // Return the current duration.
  228. return myDuration;
  229. }
  230. msclock Timeout::restart() { // Restart the timeout timer.
  231. return myTimer.start(); // Restart the clock and return the time.
  232. }
  233. msclock Timeout::getElapsedTime() { // Get elapsed milliseconds.
  234. return myTimer.getElapsedTime(); // Return the elapsed time.
  235. }
  236. msclock Timeout::getRemainingTime() { // Get remaining milliseconds.
  237. msclock remaining = 0ULL; // Assume we're expired to start.
  238. msclock elapsed = myTimer.getElapsedTime(); // Get the elapsed time.
  239. if(elapsed < myDuration) { // If there is still time then
  240. remaining = myDuration - elapsed; // calculate what is left.
  241. }
  242. return remaining; // Return what we found.
  243. }
  244. bool Timeout::isExpired() { // Return true if time is up.
  245. return (!(myTimer.getElapsedTime() < myDuration)); // Check the elapsed time against myDuration.
  246. }
  247. } // End namespace codedweller