进行简单乘法似乎lambda
更快;为什么?
import numpy as np
import time
def mult(x=None, y=None): return x*y
x = np.random.rand(10000,10000)
f = lambda z, g: z*g
start = []
end = []
for i in xrange(100):
start.append(time.time())
x*5
end.append(time.time())
start = np.array(start)
end = np.array(end)
print np.sum(end-start)/len(end)
start = []
end = []
for i in xrange(100):
start.append(time.time())
f(x, 5)
end.append(time.time())
start = np.array(start)
end = np.array(end)
print np.sum(end-start)/len(end)
start = []
end = []
for i in xrange(100):
start.append(time.time())
mult(x, 5)
end.append(time.time())
start = np.array(start)
end = np.array(end)
print np.sum(end-start)/len(end)
我得到:
0.487183141708
0.482636857033
0.483230319023
答案 0 :(得分:0)
使用timeit
模块:
import numpy as np
def mult(x=None, y=None):
return x*y
x = np.random.rand(1000, 1000)
f = lambda z, g: z*g
if __name__ == '__main__':
import timeit
setup_str = "from __main__ import x, f, mult"
print(timeit.timeit('x*5', number=100, setup=setup_str))
print(timeit.timeit('f(x, 5)', number=100, setup=setup_str))
print(timeit.timeit('mult(x, 5)', number=100, setup=setup_str))
输出
0.3345440280099865
0.42724098000326194
0.3455269880068954