# 一致性哈希算法与传统哈希算法的对比

1. 传统哈希算法

from hashlib import md5
from struct import unpack_from

ITEMS = 10000000
NODES = 100

node_stat = [0 for i in range(NODES)]

for item in range(ITEMS):
k = md5(str(item)).digest()
h = unpack_from(">I", k)[0]
n = h % NODES
node_stat[n] += 1

from hashlib import md5
from struct import unpack_from

ITEMS = 10000000
NODES = 100
NEW_NODES = 101

change = 0

for item in range(ITEMS):
k = md5(str(item)).digest()
h = unpack_from(">I", k)[0]
n = h % NODES
n_new = h % NEW_NODES
if n_new != n:
change += 1

2. 一致性哈希算法

from hashlib import md5
from struct import unpack_from
from bisect import bisect_left

ITEMS = 10000000
NODES = 100
NEW_NODES = 101

change = 0
ring = []
new_ring = []

def _hash(value):
k = md5(str(value)).digest()
ha = unpack_from(">I", k)[0]
return ha

for n in range(NODES):
ring.append(_hash(n))
ring.sort()

for n in range(NEW_NODES):
new_ring.append(_hash(n))
new_ring.sort()

for item in range(ITEMS):
h = _hash(item)
n = bisect_left(ring, h) % NODES
new_n = bisect_left(new_ring, h) % NEW_NODES
if new_n != n:
change += 1

from hashlib import md5
from struct import unpack_from
from bisect import bisect_left

ITEMS = 10000000
NODES = 100

node_stat = [0 for i in range(NODES)]
ring = []
hash2node = {}

def _hash(value):
k = md5(str(value)).digest()
ha = unpack_from(">I", k)[0]
return ha

for n in range(NODES):
h = _hash(n)
ring.append(h)
ring.sort()
hash2node[h] = n

for item in range(ITEMS):
h = _hash(item)
n = bisect_left(ring, h) % NODES
node_stat[hash2node[ring[n]]] += 1