-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathpywrr.py
66 lines (55 loc) · 1.66 KB
/
pywrr.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#########
# Author: Marcin Matlaszek <[email protected]>
# Description: Implementation of WeightedRoundRobin algorithm.
########
import random
import fractions
class WRRScheduler():
cw = 0
i = -1
data_set = []
max_s = None
gcd_s = None
len_s = None
counter = {}
def __init__(self, s = None):
self._init_dataset(s)
def _init_dataset(self, s):
self.data_set = s
self.max_s = max(s, key=lambda x: x[1])[1]
self.gcd_s = reduce(fractions.gcd, [ weight for data, weight in s])
self.len_s = len(s)
def schedule(self):
while True:
self.i = (self.i + 1) % self.len_s
if self.i == 0:
self.cw = self.cw - self.gcd_s
if self.cw <= 0:
self.cw = self.max_s
if self.cw == 0:
return None
if self.data_set[self.i][1] >= self.cw:
self._inc_counter(self.data_set[self.i])
return self.data_set[self.i]
def _inc_counter(self, item):
try:
self.counter[item[0]] += 1
except KeyError:
self.counter[item[0]] = 1
def set_data(self, s):
self.reset()
self._init_dataset(s)
def reset_counter(self):
self.counter = {}
def reset(self):
self.cw = 0
self.i = -1
self.data_set = []
self.max_s = None
self.gcd_s = None
self.len_s = None
self.reset_counter()
def get_next(self, n = 1):
if n > 1:
return [ self.schedule() for i in range(0,n) ]
return self.schedule()