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
| import random
import timeit
from functools import partial
import numpy as np
def tpl(t):
return tuple(max(x) for x in zip(*t))
def comprehension(t):
return [max(x) for x in zip(*t)]
def apd(t):
res=[]
for x in zip(*t):
res.append(max(x))
return res
def np_max(t):
return np.amax(np.array(t), axis=0)
# Le tableau témoin
m=1_000_000
temoin=[
[1, 2, 3, 8, 4] * m,
[3, 4, 5, 2, 3] * m,
[9, 1, 4, 7, 9] * m,
]
# Les fonctions à chronométrer
fct={
"tuple" : tpl,
"comprehension" : comprehension,
"append" : apd,
"np_max" : np_max
}
# Le benchmark
for (k, v) in random.sample(fct.items(), len(fct)):
t=timeit.Timer(partial(v, temoin)).repeat(repeat=2, number=2)
print("%s: min=%f, max=%f, avg=%f" % (k, min(t), max(t), sum(t)/len(t)))
# for |
Partager