Ich würde annehmen, dass die Diskrepanz ist, weil Sie Listen und Arrays in e
erstellen, während Sie nur Listen in d
erstellen. Bedenken Sie:
import numpy as np
def d():
a = [1,2,3,4,5]
b = [10,20,30,40,50]
c = [i*j for i,j in zip(a,b)]
return c
def e():
a = np.array([1,2,3,4,5])
b = np.array([10,20,30,40,50])
c = a*b
return c
#Warning: Functions with mutable default arguments are below.
# This code is only for testing and would be bad practice in production!
def f(a=[1,2,3,4,5],b=[10,20,30,40,50]):
c = [i*j for i,j in zip(a,b)]
return c
def g(a=np.array([1,2,3,4,5]),b=np.array([10,20,30,40,50])):
c = a*b
return c
import timeit
print timeit.timeit('d()','from __main__ import d')
print timeit.timeit('e()','from __main__ import e')
print timeit.timeit('f()','from __main__ import f')
print timeit.timeit('g()','from __main__ import g')
Hier werden die Funktionen f
und g
vermeiden Neuerstellung der Listen/Arrays jedes Mal um und wir bekommen sehr ähnliche Leistung:
1.53083586693
15.8963699341
1.33564996719
1.69556999207
Beachten Sie, dass die Liste-comp + zip
noch gewinnt. wenn wir die Anordnungen ausreichend groß Allerdings machen, gewinnt numpy Hände:
t1 = [1,2,3,4,5] * 100
t2 = [10,20,30,40,50] * 100
t3 = np.array(t1)
t4 = np.array(t2)
print timeit.timeit('f(t1,t2)','from __main__ import f,t1,t2',number=10000)
print timeit.timeit('g(t3,t4)','from __main__ import g,t3,t4',number=10000)
Meine Ergebnisse sind:
0.602419137955
0.0263929367065
Vielleicht verwandt: http://stackoverflow.com/questions/5956783/numpy-float-10x-slower-than-butintin-in-arithmetic- operations –
sollten Sie größere Array für diese Art von Test verwenden –