負載均衡,隨機加權重演算法實現
阿新 • • 發佈:2018-12-09
例如輸入資料 [(“a”,3),(“b”,3),(“c”,9),(“d”,1)], 權重分別為3,3,9,1
具體演算法是將3,3,9,1 對映到一維座標中,0-3-6-15-16,取得一個隨機數,範圍是0,16, 看結果落在哪個區間就返回哪個數值
已下以python程式碼為例子:
import random import collections
def get_seq(inputData): head = 0 output=[] for i in inputData: head += i[1] output.append((i[0],head)) return head, output
def get_value(maxValue, seq): r = random.randint(0,maxValue) for i in seq: if r <= i[1]: return i[0]
Test program
test = [(“a”,3),(“b”,3),(“c”,9),(“d”,1)] m, s = get_seq(test)
p = [] for i in range(10000): p.append(get_value(m, s))
print(collections.Counter(p))
Test result
Counter({‘c’: 5340, ‘a’: 2310, ‘b’: 1756, ‘d’: 594})