高性能Python-Namespaces

2016-09-16  本文已影响30人  三千万星辰

算是一个小Tips

当一个变量、函数、module被Python引用时,Python有一个顺序去寻找这些对象。

例子:

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

test3的编码不太pythonic,尽可能采用test2的方法

上一篇 下一篇

猜你喜欢

热点阅读