在 python 中,当将纯递归函数更改为递归生成器(不是普通生成器)时,性能似乎正在下降。
例如,以下是查找列表所有组合的两个函数之间的性能比较:
from datetime import datetime as dt
def rec_subsets(ms, i=0, s=[]):
if i == len(ms):
# do something with s
return
rec_subsets(ms, i+1, s)
rec_subsets(ms, i+1, s + [ms[i]])
def gen_subsets(ms, i=0, s=[]):
if i == len(ms):
yield s
return
for a in gen_subsets(ms, i+1, s): yield a
for a in gen_subsets(ms, i+1, s + [ms[i]]): yield a
t1 = dt.now()
rec_subsets(range(20))
t2 = dt.now()
print t2 - t1
t1 = dt.now()
for _ in gen_subsets(range(20)): pass
t2 = dt.now()
print t2 - t1
具有以下输出:
0:00:01.027000 # rec_subsets
0:00:02.860000 # gen_subsets
人们自然会期望gen_subsets大约与rec_subsets一样快,但事实并非如此,它要慢得多。
这是正常的还是我错过了什么?