![](/img/trans.png)
[英]Python - Optimal way to re-assign global variables from function in other module
[英]What's the optimal way to use global variables in python?
python
中的global
變量比local
變量慢的事實是眾所周知的,並且已經在本網站的不同問題中進行了討論。 但是,我仍然沒有找到答案的一件事是,在代碼中的不同函數中使用global
變量(如constant
,python 中不存在的概念)的最佳和最快方法是什么?
到目前為止,我能找到的最佳解決方案是定義一個closure
function ,在其中我將全局變量分配給本地變量。
from timeit import timeit
number = 10
def flocal():
number = 10
for i in range(25):
x = number
def fglobal():
for i in range(25):
x = number
def fglobal_wrapper():
global_number = number
def actual_func():
for i in range(25):
x = global_number
return actual_func
fclosure = fglobal_wrapper()
print("local: %.3f" % timeit("flocal()", "from __main__ import flocal"))
print("global: %.3f" % timeit("fglobal()", "from __main__ import fglobal"))
print("closure: %.3f" % timeit("fclosure()", "from __main__ import fclosure"))
Output:
local: 0.681
global: 0.806
closure: 0.728
但這是一個丑陋的解決方案,而且它仍然比使用局部變量慢。 在函數內部使用等效的全局/常量變量的最佳方法是什么,而不必使用將它們作為 arguments 傳遞給 function 或這種closure
解決方法?
def fglobal2():
global_number = number # single access to global
for i in range(25):
x = global_number
在我的機器上和本地一樣快(我運行了 10 倍以上的測試以減少時間估計中的噪音)
local: 4.409
global: 4.914
global2: 4.406 # proposed, as fast as local
closure: 4.560
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.