Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

timing.cpp 20KB

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