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
| #!/usr/bin/env python
# coding: utf-8
nb=2_000_000
prec=len(str(nb))
mot_fr_l=tuple("fr_%*d" % (prec, i) for i in range(nb))
mot_en_l=tuple("en_%*d" % (prec, i) for i in range(nb))
mot_list=(mot_fr_l, mot_en_l)
mot_dict=dict(("fr_%*d" % (prec, i), "en_%*d" % (prec, i)) for i in range(nb))
import bisect
def algo_list(mots, key):
idx=bisect.bisect_left(mots[0], key)
if idx == len(mots[0]): return None
return mots[1][idx]
def algo_dict(mots, key): return mots.get(key)
import timeit
import random
from functools import partial
# Les fonctions à tester
fct={
"list" : partial(algo_list, mot_list),
"dict" : partial(algo_dict, mot_dict),
}
# Le nombre de répétitions
repeat=20
print("taille data=%d, repeat=%d" % (nb, repeat))
# Mot dans la première moitié
for (k, v) in random.sample(tuple(fct.items()), len(fct)):
# Création du mot à chercher
find="fr_%*d" % (prec, random.randint(0, nb // 2))
# Vérification algorithmes renvoient la même valeur
assert fct["list"](find) == fct["dict"](find)
t=timeit.Timer(partial(v, find)).repeat(repeat=repeat, number=500_000)
print("avec mot première moitié: %s: min=%f, max=%f, avg=%f" % (k, min(t), max(t), sum(t)/len(t)))
# for
# Mot dans la seconde moitié
for (k, v) in random.sample(tuple(fct.items()), len(fct)):
# Création du mot à chercher
find="fr_%*d" % (prec, random.randint(nb // 2, nb-1))
# Vérification algorithmes renvoient la même valeur
assert fct["list"](find) == fct["dict"](find)
t=timeit.Timer(partial(v, find)).repeat(repeat=repeat, number=500_000)
print("avec mot seconde moitié: %s: min=%f, max=%f, avg=%f" % (k, min(t), max(t), sum(t)/len(t)))
# for
# Mot inexistant
for (k, v) in random.sample(tuple(fct.items()), len(fct)):
# Création du mot à chercher
find="fr_xxx"
# Vérification algorithmes renvoient la même valeur
assert fct["list"](find) == fct["dict"](find)
t=timeit.Timer(partial(v, find)).repeat(repeat=repeat, number=500_000)
print("avec mot non existant: %s: min=%f, max=%f, avg=%f" % (k, min(t), max(t), sum(t)/len(t)))
# for |
Partager