Advertisement
Guest User

Untitled

a guest
Jun 20th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. from datetime import datetime
  2.  
  3.  
  4. class Ticker:
  5.  
  6. # 1,000,000; a one followed by six zeroes
  7. microseconds_per_second = 1000000
  8.  
  9. def __init__(self, tps=1):
  10. self.tps = tps
  11. self._last_mark = 0
  12. self._accumulator = 0
  13.  
  14. @property
  15. def tps(self):
  16. return self._tps
  17.  
  18. @tps.setter
  19. def tps(self, ticks_per_second):
  20. assert int(ticks_per_second) == ticks_per_second
  21. assert 0 < ticks_per_second
  22. self._tps = ticks_per_second
  23.  
  24. @property
  25. def last_mark(self):
  26. return self._last_mark
  27.  
  28. @property
  29. def _microseconds_per_tick(self):
  30. return Ticker.microseconds_per_second / self.tps
  31.  
  32. def tick(self):
  33. """Returns the number of unprocessed ticks.
  34.  
  35. First call will initialize clock by setting first mark.
  36. This first call will return -1. All other calls will
  37. return an integer greater than or equal to zero.
  38.  
  39. """
  40. if not self.last_mark:
  41. # Set firt time mark and exit.
  42. self._last_mark = datetime.now()
  43. return -1
  44.  
  45. # Get dt, the change in time, and update mark.
  46. next_mark = datetime.now()
  47. dt = next_mark - self._last_mark
  48. self._last_mark = next_mark
  49.  
  50. # Increment accumulator by change in time:
  51. # 1) the seconds, which are converted to microseconds.
  52. # 2) the microseconds, which total less than one second.
  53. self._accumulator += (dt.seconds * Ticker.microseconds_per_second)
  54. self._accumulator += dt.microseconds
  55.  
  56. # Drain full ticks from accumulator and return count.
  57. ticks_elapsed = 0
  58. while self._accumulator >= self._microseconds_per_tick:
  59. self._accumulator -= self._microseconds_per_tick
  60. ticks_elapsed += 1
  61. return ticks_elapsed
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement