[英]Speed of global and local variables in Python
我猜每個人都知道:
Python比全局變量更有效地訪問局部變量
好的,這是真的:
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μs
%%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μs
如何解釋這些測試?
在最后一個示例中,首先定義一個額外的函數。 如果在找到功能后啟動計時器,它應該更快。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.