Subversion Repositories svnkaklik

Rev

Details | Last modification | View Log

Rev Author Line No. Line
36 kaklik 1
# Written by Bram Cohen
2
# see LICENSE.txt for license information
3
 
4
from clock import clock
5
try:
6
    True
7
except:
8
    True = 1
9
    False = 0
10
 
11
FACTOR = 0.999
12
 
13
class RateMeasure:
14
    def __init__(self):
15
        self.last = None
16
        self.time = 1.0
17
        self.got = 0.0
18
        self.remaining = None
19
        self.broke = False
20
        self.got_anything = False
21
        self.last_checked = None
22
        self.rate = 0
23
 
24
    def data_came_in(self, amount):
25
        if not self.got_anything:
26
            self.got_anything = True
27
            self.last = clock()
28
            return
29
        self.update(amount)
30
 
31
    def data_rejected(self, amount):
32
        pass
33
 
34
    def get_time_left(self, left):
35
        t = clock()
36
        if not self.got_anything:
37
            return None
38
        if t - self.last > 15:
39
            self.update(0)
40
        try:
41
            remaining = left/self.rate
42
            delta = max(remaining/20,2)
43
            if self.remaining is None:
44
                self.remaining = remaining
45
            elif abs(self.remaining-remaining) > delta:
46
                self.remaining = remaining
47
            else:
48
                self.remaining -= t - self.last_checked
49
        except ZeroDivisionError:
50
            self.remaining = None
51
        if self.remaining is not None and self.remaining < 0.1:
52
            self.remaining = 0.1
53
        self.last_checked = t
54
        return self.remaining
55
 
56
    def update(self, amount):
57
        t = clock()
58
        t1 = int(t)
59
        l1 = int(self.last)
60
        for i in xrange(l1,t1):
61
            self.time *= FACTOR
62
            self.got *= FACTOR
63
        self.got += amount
64
        if t - self.last < 20:
65
            self.time += t - self.last
66
        self.last = t
67
        try:
68
            self.rate = self.got / self.time
69
        except ZeroDivisionError:
70
            pass