home *** CD-ROM | disk | FTP | other *** search
/ Chip 2006 June / CHIP 2006-06.2.iso / program / freeware / Democracy-0.8.2.exe / xulrunner / python / BitTorrent / RateMeasure.py < prev    next >
Encoding:
Python Source  |  2006-04-10  |  2.0 KB  |  64 lines

  1. # The contents of this file are subject to the BitTorrent Open Source License
  2. # Version 1.0 (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.  
  11. # Written by Bram Cohen
  12.  
  13. from time import time
  14.  
  15.  
  16. class RateMeasure(object):
  17.  
  18.     def __init__(self, left):
  19.         self.start = None
  20.         self.last = None
  21.         self.rate = 0
  22.         self.remaining = None
  23.         self.left = left
  24.         self.broke = False
  25.         self.got_anything = False
  26.  
  27.     def data_came_in(self, amount):
  28.         if not self.got_anything:
  29.             self.got_anything = True
  30.             self.start = time() - 2
  31.             self.last = self.start
  32.             self.left -= amount
  33.             return
  34.         self.update(time(), amount)
  35.  
  36.     def data_rejected(self, amount):
  37.         self.left += amount
  38.  
  39.     def get_time_left(self):
  40.         if not self.got_anything:
  41.             return None
  42.         t = time()
  43.         if t - self.last > 15:
  44.             self.update(t, 0)
  45.         return self.remaining
  46.  
  47.     def get_size_left(self):
  48.         return self.left
  49.  
  50.     def update(self, t, amount):
  51.         self.left -= amount
  52.         try:
  53.             self.rate = ((self.rate * (self.last - self.start)) + amount) / (t - self.start)
  54.             self.last = t
  55.             self.remaining = self.left / self.rate
  56.             if self.start < self.last - self.remaining:
  57.                 self.start = self.last - self.remaining
  58.         except ZeroDivisionError:
  59.             self.remaining = None
  60.         if self.broke and self.last - self.start < 20:
  61.             self.start = self.last - 20
  62.         if self.last - self.start > 20:
  63.             self.broke = True
  64.