使用高阶函数和 Lambda 会使运行时间和内存效率更好还是更差? 例如,将列表中的所有数字相乘:
nums = [1,2,3,4,5]
prod = 1
for n in nums:
prod*=n
对比
prod2 = reduce(lambda x,y:x*y , nums)
除了代码行数较少/使用函数式方法外,HOF 版本是否比循环版本有任何优势?
编辑:
我无法将此添加为答案,因为我没有所需的声誉。 我按照@DSM 的建议使用 timeit 来分析循环和 HOF 方法
def test1():
s= """
nums = [a for a in range(1,1001)]
prod = 1
for n in nums:
prod*=n
"""
t = timeit.Timer(stmt=s)
return t.repeat(repeat=10,number=100)
def test2():
s="""
nums = [a for a in range(1,1001)]
prod2 = reduce(lambda x,y:x*y , nums)
"""
t = timeit.Timer(stmt=s)
return t.repeat(repeat=10,number=100)
这是我的结果:
Loop:
[0.08340786340144211, 0.07211491653462579, 0.07162720686361926, 0.06593182661083438, 0.06399049758613146, 0.06605228229559557, 0.06419744588664211, 0.0671893658461038, 0.06477527090075941, 0.06418023793167627]
test1 average: 0.0644778902685
HOF:
[0.0759414223099324, 0.07616920129277016, 0.07570730355421262, 0.07604965128984942, 0.07547092059389193, 0.07544737286604364, 0.075532959799953, 0.0755039779810629, 0.07567424616704144, 0.07542563650187661]
test2 average: 0.0754917512762
平均循环方法似乎比使用 HOF 更快。
最佳答案
高阶函数可以非常快。
例如,map(ord, somebigstring)
比等效的列表推导[ord(c) for c in somebigstring]快很多
。前者获胜的三个原因:
map() 将结果字符串的大小预先设置为 somebigstring 的长度。相比之下,列表理解必须在其增长时多次调用 realloc()。
map() 只需对 ord 进行一次查找,首先检查全局变量,然后检查并在内置函数中找到它。列表理解必须在每次迭代中重复这项工作。
map 的内部循环以 C 速度运行。列表理解的循环体是一系列纯 Python 步骤,每个步骤都需要由 eval 循环分派(dispatch)或处理。
以下是确认预测的一些时间:
>>> from timeit import Timer
>>> print min(Timer('map(ord, s)', 's="x"*10000').repeat(7, 1000))
0.808364152908
>>> print min(Timer('[ord(c) for c in s]', 's="x"*10000').repeat(7, 1000))
1.2946639061
关于python - 高阶函数与循环——运行时间和内存效率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9042174/