Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

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. // 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. #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64)
  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. return MillisecondsToSleep; // Return the set value.
  79. }
  80. int Sleeper::getMillisecondsToSleep() { // Safe way to get the value.
  81. return MillisecondsToSleep; // Send back the value.
  82. }
  83. void Sleeper::sleep() { // Here's where we snooze.
  84. if(MillisecondsToSleep > 0) { // If we have a good snooze
  85. doRawSleep(MillisecondsToSleep); // value then go to Sleep().
  86. } else { // If the value is not good
  87. throw BadSleeperValue(); // throw an exception.
  88. }
  89. }
  90. void Sleeper::sleep(int x) { // Reset the sleep time then sleep.
  91. setMillisecondsToSleep(x); // Set the sleep time.
  92. sleep(); // Sleep.
  93. }
  94. void Sleeper::operator()() { // Syntactic sugar - operator() on
  95. sleep(); // a sleeper calls sleep().
  96. }
  97. ///////////////////////////////////////////////////////////////////////////////
  98. // class PollTimer - An object to pause during polling processes where the
  99. // time between polls is expanded according to a Fibonacci sequence. This
  100. // allows self organizing automata to relax a bit when a particular process
  101. // is taking a long time so that the resources used in the polling process are
  102. // reduced if the system is under load - The idea is to prevent the polling
  103. // process from loading the system when there are many nodes poling, yet to
  104. // allow for a rapid response when there are few or when the answer we're
  105. // waiting for is ready quickly. We use a Fibonacci expansion because it is
  106. // a natural spiral.
  107. ///////////////////////////////////////////////////////////////////////////////
  108. PollTimer::PollTimer(int Nom, int Max) :
  109. NominalPollTime(MinimumSleeperTime),
  110. MaximumPollTime(MinimumSleeperTime) { // Construction requires a
  111. setNominalPollTime(Nom); // nominal delay to use and
  112. setMaximumPollTime(Max); // a maximum delay to allow.
  113. }
  114. int PollTimer::setNominalPollTime(int Nom) { // Set the Nominal Poll Time.
  115. if(Nom < MinimumSleeperTime || // Check the low and high
  116. Nom > MaximumSleeperTime) // limits and throw an
  117. throw BadPollTimerValue(); // exception if we need to.
  118. // If the value is good then
  119. NominalPollTime = Nom; // remember it.
  120. if(MaximumPollTime < NominalPollTime) // Make sure the Maximum poll
  121. MaximumPollTime = NominalPollTime; // time is >= the Nominal time.
  122. reset(); // Reset due to the change.
  123. return NominalPollTime; // Return the new value.
  124. }
  125. int PollTimer::setMaximumPollTime(int Max) { // Set the Maximum Poll Time.
  126. if(Max < MinimumSleeperTime || // Check the low and high
  127. Max > MaximumSleeperTime) // limits and throw an
  128. throw BadPollTimerValue(); // exception if we need to.
  129. // If the value is good then
  130. MaximumPollTime = Max; // remember it.
  131. if(MaximumPollTime < NominalPollTime) // Make sure the Maximum poll
  132. MaximumPollTime = NominalPollTime; // time is >= the Nominal time.
  133. reset(); // Reset due to the change.
  134. return MaximumPollTime; // Return the new value.
  135. }
  136. void PollTimer::reset() { // Reset the spiral.
  137. FibA = NominalPollTime; // Assume our starting event.
  138. FibB = 0; // Assume no other events.
  139. LimitReached=false; // Reset our limit watcher.
  140. }
  141. int PollTimer::pause() { // Pause between polls.
  142. int SleepThisTime = MaximumPollTime; // Assume we're at out limit for now.
  143. if(LimitReached) { // If actually are at our limit then
  144. mySleeper.sleep(SleepThisTime); // use the current value.
  145. } else { // If we are still expanding then
  146. SleepThisTime = FibA+FibB; // Calculate the time to use and
  147. if(SleepThisTime >= MaximumPollTime) { // check it against the limit. If
  148. SleepThisTime = MaximumPollTime; // we reached the limit, us that value
  149. LimitReached = true; // and set the flag.
  150. } else { // If we haven't reached the limit yet
  151. FibB=FibA; // then shift our events and remember
  152. FibA=SleepThisTime; // this one to build our spiral.
  153. }
  154. mySleeper.sleep(SleepThisTime); // Take a nap.
  155. } // Then FIRE THE MISSILES!
  156. return SleepThisTime; // Tell the caller how long we slept.
  157. }
  158. ///////////////////////////////////////////////////////////////////////////////
  159. // class Timer - This one acts much like a stop watch with millisecond
  160. // resolution. The time is based on wall-clock time using gettimeofday().
  161. ///////////////////////////////////////////////////////////////////////////////
  162. #ifdef WIN32
  163. // Here is the win32 version of getLocalRawClock()
  164. #define TimerIsUnixBased (false)
  165. msclock Timer::getLocalRawClock() const {
  166. FILETIME t; // We need a FILETIME structure.
  167. msclock c; // We need a place to calculate our value.
  168. GetSystemTimeAsFileTime(&t); // Grab the system time.
  169. c = (unsigned long long int) t.dwHighDateTime << 32LL; // Put full seconds into the high order bits.
  170. c |= t.dwLowDateTime; // Put 100ns ticks into the low order bits.
  171. c /= 10000; // Divide 100ns ticks by 10K to get ms.
  172. c -= EPOCH_DELTA_IN_MSEC; // Correct for the epoch difference.
  173. return c; // Return the result.
  174. }
  175. #else
  176. // Here is the unix/posix version of getLocalRawClock()
  177. #define TimerIsUnixBased (true)
  178. msclock Timer::getLocalRawClock() const {
  179. struct timeval t; // We need a timval structure.
  180. msclock c; // We need a place to calculate our value.
  181. gettimeofday(&t,NULL); // Grab the system time.
  182. c = t.tv_sec * 1000; // Put the full seconds in as milliseconds.
  183. c += t.tv_usec / 1000; // Add the microseconds as milliseconds.
  184. return c; // Return the milliseconds.
  185. }
  186. #endif
  187. Timer::Timer() { // Construct by resetting the
  188. start(); // clocks by using start();
  189. }
  190. Timer::Timer(msclock startt): // Construct a timer from a specific time.
  191. RunningFlag(true), // Set the running flag,
  192. StartTime(startt), // the start time and
  193. StopTime(startt) { // the stop time clock to startt.
  194. }
  195. void Timer::clear() { // Stop, zero elapsed, now.
  196. StartTime = StopTime = getLocalRawClock(); // Set the start and stop time
  197. RunningFlag = false; // to now. We are NOT running.
  198. }
  199. msclock Timer::start() { // (re) Start the timer at this moment.
  200. return start(getLocalRawClock()); // start() using the current raw clock.
  201. }
  202. msclock Timer::start(msclock startt) { // (re) Start a timer at startt.
  203. StartTime = StopTime = startt; // Set the start and end clocks.
  204. RunningFlag = true; // Set the running flag to true.
  205. return StartTime; // Return the start clock.
  206. }
  207. msclock Timer::getStartClock() { return StartTime; } // Return the start clock value.
  208. bool Timer::isRunning() { return RunningFlag; } // Return the running state.
  209. msclock Timer::getElapsedTime() const { // Return the elapsed timeofday -
  210. msclock AssumedStopTime; // We need to use a StopTime simulation.
  211. if(RunningFlag) { // If we are running we must get
  212. AssumedStopTime = getLocalRawClock(); // the current time (as if it were stop).
  213. } else { // If we are not running we use
  214. AssumedStopTime = StopTime; // the actual stop time.
  215. }
  216. msclock delta = AssumedStopTime - StartTime; // Calculate the difference.
  217. return delta; // That's our result.
  218. }
  219. msclock Timer::stop() { // Stop the timer.
  220. StopTime = getLocalRawClock(); // Grab the time and then stop
  221. RunningFlag=false; // the clock.
  222. return StopTime; // Return the time we stopped.
  223. }
  224. msclock Timer::getStopClock() { return StopTime; } // Return the stop clock value.
  225. double Timer::getElapsedSeconds() const { // Calculate the elapsed seconds.
  226. msclock e = getElapsedTime(); // Get the elapsed time in msecs.
  227. double secs = (double) e / 1000.0; // Calculate seconds from msecs.
  228. return secs;
  229. }
  230. bool Timer::isUnixBased() { return TimerIsUnixBased; } // Is this timer unix based?
  231. msclock Timer::toWindowsEpoch(msclock unixt) { // Convert a unix based msclock to win32 based.
  232. return (unixt + EPOCH_DELTA_IN_MSEC); // Going this way we add the epoch delta.
  233. }
  234. msclock Timer::toUnixEpoch(msclock win32t) { // Convert a win32 based msclock to a unix based.
  235. return (win32t - EPOCH_DELTA_IN_MSEC); // Going this way we subtract the epoch delta.
  236. }
  237. ///////////////////////////////////////////////////////////////////////////////
  238. // class Timeout - This one uses a Timer to establish a timeout value.
  239. ///////////////////////////////////////////////////////////////////////////////
  240. Timeout::Timeout(msclock duration):myDuration(duration) { } // Create, set the duration, start.
  241. msclock Timeout::setDuration(msclock duration) { // Set/Change the duration in milliseconds.
  242. myDuration = duration; // (re) Set the duration.
  243. return myDuration; // Return the current (new) duration.
  244. }
  245. msclock Timeout::getDuration() { // Return the current duration.
  246. return myDuration;
  247. }
  248. msclock Timeout::restart() { // Restart the timeout timer.
  249. return myTimer.start(); // Restart the clock and return the time.
  250. }
  251. msclock Timeout::getElapsedTime() { // Get elapsed milliseconds.
  252. return myTimer.getElapsedTime(); // Return the elapsed time.
  253. }
  254. msclock Timeout::getRemainingTime() { // Get remaining milliseconds.
  255. msclock remaining = 0ULL; // Assume we're expired to start.
  256. msclock elapsed = myTimer.getElapsedTime(); // Get the elapsed time.
  257. if(elapsed < myDuration) { // If there is still time then
  258. remaining = myDuration - elapsed; // calculate what is left.
  259. }
  260. return remaining; // Return what we found.
  261. }
  262. bool Timeout::isExpired() { // Return true if time is up.
  263. return (!(myTimer.getElapsedTime() < myDuration)); // Check the elapsed time against myDuration.
  264. }