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

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