高性能Python-Namespaces

算是一个小Tips

当一个变量、函数、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的方法

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.元类 1.1.1类也是对象 在大多数编程语言中,类就是一组用来描述如何生成一个对象的代码段。在Python中这...
    TENG书阅读 5,113评论 0 3
  • 前言 Python的创始人为Guido van Rossum。1989年圣诞节期间,在阿姆斯特丹,Guido为了打...
    依依玖玥阅读 8,929评论 6 37
  • MongoDB常用操作 一、查询 find方法 查询所有的结果: select * from users;===d...
    止风者阅读 3,690评论 1 3
  • Python进阶框架 希望大家喜欢,点赞哦首先感谢廖雪峰老师对于该课程的讲解 一、函数式编程 1.1 函数式编程简...
    Gaolex阅读 10,862评论 6 53
  • 2017年1月1日,新年第一天,小晴。 七点二十。照例闹钟叫醒,问候早安。起床,洗漱,早餐,收拾,出门。 九点。准...
    何夕何处何人阅读 3,081评论 0 3