我更喜欢在 Python 中尽可能使用嵌套函数而不是方法或全局函数。所以我决定测试它们的性能,因为它接缝当你在另一个函数中定义一个函数时,每次调用外部函数时定义内部函数都会产生开销。
充其量我希望全局函数稍微快一点,但令人惊讶的是嵌套函数更快。有谁知道为什么?
这是我的代码:
from time import clock
def a(n):
return n + 1
def b1(loopcount):
return sum([a(n) for n in range(loopcount)])
def b2(loopcount):
def a(n):
return n + 1
return sum([a(n) for n in range(loopcount)])
powers = [5, 6, 7]
b1times = []
b2times = []
print " ", "".join(["{:^10d}".format(n) for n in powers])
for i in range(5):
for power in powers:
t = clock()
b1(10**power)
b1times.append(clock() - t)
for power in powers:
t = clock()
b2(10**power)
b2times.append(clock() - t)
print "b1:", "".join(["{:^10.5f}".format(n) for n in b1times])
print "b2:", "".join(["{:^10.5f}".format(n) for n in b2times])
print ""
b1times = []
b2times = []
这是我电脑上的结果:
5 6 7
b1: 0.08200 0.82773 8.47946
b2: 0.06914 0.79637 8.18571
b1: 0.07332 0.82139 8.68262
b2: 0.06547 0.82088 8.19606
b1: 0.07963 0.82625 9.65037
b2: 0.06617 0.82027 8.21412
b1: 0.07630 0.82112 8.49082
b2: 0.06541 0.80686 8.20532
b1: 0.12328 0.87034 8.42964
b2: 0.07059 0.79717 8.24620
更新:使用@Janne Karila 的评论
现在我更多地调用 b1 和 b2,b1 变得更快。所以正如@Kos 和@Pavel Anossov 在他们的回答中所说,有几个因素会影响这里的速度,你不能做出一般性的陈述。
谢谢大家!
from time import *
def a1(n):
return n + 1
def b1(n):
return a1(n)
def b2(n):
def a2():
return n + 1
return a2()
powers = [4, 5, 6]
b1times = []
b2times = []
print " ", "".join(["{:^10d}".format(n) for n in powers])
for i in range(5):
for power in powers:
t = clock()
sum([b1(n) for n in range(10**power)])
b1times.append(clock() - t)
for power in powers:
t = clock()
sum([b2(n) for n in range(10**power)])
b2times.append(clock() - t)
print "b1:", "".join(["{:^10.5f}".format(n) for n in b1times])
print "b2:", "".join(["{:^10.5f}".format(n) for n in b2times])
print ""
b1times = []
b2times = []