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
| #!/usr/bin/env python3
# coding: utf-8
import random
import timeit
from functools import partial
# Initialisation random
random.seed()
# Les fonctions à tester
def svear(l, b):
idx=[x[0] for x in l].index(b)
return l[idx][1]
def wiz(l, b):
(u, v)=zip(*l)
return v[u.index(b)]
fct={
"svear" : svear,
"wiz" : wiz,
}
# Les données à traiter
import string
data=list(zip(string.ascii_letters, range(1, len(string.ascii_letters)+1)))
# Vérification fonctions donnent résultats identiques
for b in random.sample(string.ascii_letters, 10):
assert svear(data, b) == wiz(data, b)
# Le nombre de répétitions (les moyennes se feront sur cette valeur)
repeat=20
# Appel des fonctions dans un ordre aléatoire et affichage du chrono
print("taille data=%d, repeat=%d" % (len(data), repeat))
for (k, v) in random.sample(tuple(fct.items()), len(fct)):
b=random.sample(string.ascii_letters, 1)[0]
t=timeit.Timer(partial(v, data, b)).repeat(repeat=repeat, number=500_000)
print("%s: min=%f, max=%f, avg=%f" % (k, min(t), max(t), sum(t)/len(t)))
# for |