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 / CurrentRateMeasure.py < prev    next >
Encoding:
Python Source  |  2006-04-10  |  1.5 KB  |  49 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 Measure(object):
  17.  
  18.     def __init__(self, max_rate_period, fudge=5):
  19.         self.max_rate_period = max_rate_period
  20.         self.ratesince = time() - fudge
  21.         self.last = self.ratesince
  22.         self.rate = 0.0
  23.         self.total = 0
  24.  
  25.     def update_rate(self, amount):
  26.         self.total += amount
  27.         t = time()
  28.         self.rate = (self.rate * (self.last - self.ratesince) + 
  29.             amount) / (t - self.ratesince)
  30.         self.last = t
  31.         if self.ratesince < t - self.max_rate_period:
  32.             self.ratesince = t - self.max_rate_period
  33.  
  34.     def get_rate(self):
  35.         self.update_rate(0)
  36.         return self.rate
  37.  
  38.     def get_rate_noupdate(self):
  39.         return self.rate
  40.  
  41.     def time_until_rate(self, newrate):
  42.         if self.rate <= newrate:
  43.             return 0
  44.         t = time() - self.ratesince
  45.         return ((self.rate * t) / newrate) - t
  46.  
  47.     def get_total(self):
  48.         return self.total
  49.