我想每个人都知道:
Python accesses local variables much more efficiently than global variables
好的,这是真的:
oldlist = [str(i) for i in range(500)]
oldlist1 = [i for i in range(500)]
%%timeit
newlist = []
for word in oldlist:
newlist.append(word.upper())
10000 次循环,最好的 3 次:每次循环 178 微秒
%%timeit
def func():
newlist = []
for word in oldlist:
newlist.append(word.upper())
return newlist
newlist = func()
10000 次循环,最好的 3 次:每次循环 93.2 µs
不幸的是,看起来这不是全局规则而是特例:
%%timeit
newlist = []
for nr in oldlist1:
newlist.append(nr * nr)
10000 次循环,最好的 3 次:每次循环 60.3 µs
%%timeit
def func():
newlist = []
for nr in oldlist1:
newlist.append(nr * nr)
return newlist
newlist = func()
10000 次循环,最好的 3 次:每次循环 60.5 微秒
如何解释这些测试?
最佳答案
在上一个示例中,您首先定义了一个额外的函数。如果您在找到函数后启动计时器,它应该会更快。
关于python - Python中全局变量和局部变量的速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20075044/