1
0

CurrentRateMeasure.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. # The contents of this file are subject to the BitTorrent Open Source License
  2. # Version 1.1 (the License). You may not copy or use this file, in either
  3. # source code or executable form, except in compliance with the License. You
  4. # may obtain a copy of the License at http://www.bittorrent.com/license/.
  5. #
  6. # Software distributed under the License is distributed on an AS IS basis,
  7. # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  8. # for the specific language governing rights and limitations under the
  9. # License.
  10. # Written by Bram Cohen
  11. from BTL.platform import bttime
  12. class CurrentRateMeasure(object):
  13. def __init__(self, max_rate_period, fudge=5):
  14. self.max_rate_period = max_rate_period
  15. self.ratesince = bttime() - fudge
  16. self.last = self.ratesince
  17. self.rate = 0.0
  18. self.total = 0
  19. self.when_next_expected = bttime() + fudge
  20. def add_amount(self, amount):
  21. """ add number of bytes received """
  22. self.total += amount
  23. t = bttime()
  24. if t < self.when_next_expected and amount == 0:
  25. return self.rate
  26. self.rate = (self.rate * (self.last - self.ratesince) +
  27. amount) / (t - self.ratesince)
  28. self.last = t
  29. self.ratesince = max(self.ratesince, t - self.max_rate_period)
  30. self.when_next_expected = t + min((amount / max(self.rate, 0.0001)), 5)
  31. def get_rate(self):
  32. """ returns bytes per second """
  33. self.add_amount(0)
  34. return self.rate
  35. def get_rate_noupdate(self):
  36. """ returns bytes per second """
  37. return self.rate
  38. def time_until_rate(self, newrate):
  39. if self.rate <= newrate:
  40. return 0
  41. t = bttime() - self.ratesince
  42. # as long as the newrate is lower than rate, we wait
  43. # longer before throttling.
  44. return ((self.rate * t) / newrate) - t
  45. def get_total(self):
  46. return self.total