Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:“lambda”为什么比函数或乘法快?_Python_Function_Numpy_Lambda - Fatal编程技术网

Python:“lambda”为什么比函数或乘法快?

Python:“lambda”为什么比函数或乘法快?,python,function,numpy,lambda,Python,Function,Numpy,Lambda,做简单的乘法似乎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.ti

做简单的乘法似乎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.3345440280099865

0.42724098000326194

0.3455269880068954


您应该使用timeit对代码进行基准测试:您应该使用来测量性能,然后粘贴差异。我得到x*5 454 ms±4.86 ms/循环,fx,5 472 ms±17.3 ms/循环和multf,5 458 ms±5 ms/循环…这些差异在统计上并不显著,因此在一台特定的机器上,以特定的顺序运行一次,为lambda提供了一个比其他两个时间稍小的时间。这并不能很好地证明lambda跑得更快。我建议运行几次,并改变脚本中执行三个计时的顺序。然后,您可以进行统计测试,以发现您看到的任何差异是否显著。如果lambda在数百次运行中始终保持较快的速度,不管顺序如何,那么可能有一些值得研究的地方。看起来lambda是最慢的。
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))