算是一個小Tips
當(dāng)一個變量腿堤、函數(shù)阀坏、module被Python引用時,Python有一個順序去尋找這些對象笆檀。
- 首先忌堂,先尋找locals(),速度很快酗洒,非dictionaries查詢
- 其次士修,再尋找globals()枷遂,速度居中,dictionaries查詢
- 最后棋嘲,尋找builtin酒唉,速度最慢
例子:
import math
from math import sin
def test1(x):
return math.sin(x)
def test2(x):
return sin(x)
def test3(x, sin=math.sin):
return sin(x)
#import timeit
#print(timeit.timeit('test1(100)', 'from __main__ import test1', number = 1000000))
#print(timeit.timeit('test2(100)', 'from __main__ import test2', number = 1000000))
#print(timeit.timeit('test3(100)', 'from __main__ import test3', number = 1000000))
import dis
print(dis.dis(test1))
print(dis.dis(test2))
print(dis.dis(test3))
(env) localhost:highperf wenyong$ python tname.py
6 0 LOAD_GLOBAL 0 (math)
3 LOAD_ATTR 1 (sin)
6 LOAD_FAST 0 (x)
9 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
12 RETURN_VALUE
None
9 0 LOAD_GLOBAL 0 (sin)
3 LOAD_FAST 0 (x)
6 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
9 RETURN_VALUE
None
12 0 LOAD_FAST 1 (sin)
3 LOAD_FAST 0 (x)
6 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
9 RETURN_VALUE
None
- test1, 兩次dictionaries查詢,一次查詢math封字,一次查詢math.sin黔州,速度最慢
- test2耍鬓,一次dictionaries查詢(math.sin)阔籽,速度居中
- test3,一次local查詢牲蜀,速度最快
test3的編碼不太pythonic笆制,盡可能采用test2的方法