高性能Python-Namespaces

算是一個(gè)小Tips

當(dāng)一個(gè)變量、函數(shù)、module被Python引用時(shí),Python有一個(gè)順序去尋找這些對(duì)象。

  • 首先,先尋找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的方法

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1.元類 1.1.1類也是對(duì)象 在大多數(shù)編程語(yǔ)言中,類就是一組用來(lái)描述如何生成一個(gè)對(duì)象的代碼段。在Python中這...
    TENG書閱讀 1,417評(píng)論 0 3
  • 前言 Python的創(chuàng)始人為Guido van Rossum。1989年圣誕節(jié)期間,在阿姆斯特丹,Guido為了打...
    依依玖玥閱讀 3,699評(píng)論 6 37
  • MongoDB常用操作 一、查詢 find方法 查詢所有的結(jié)果: select * from users;===d...
    止風(fēng)者閱讀 649評(píng)論 1 3
  • Python進(jìn)階框架 希望大家喜歡,點(diǎn)贊哦首先感謝廖雪峰老師對(duì)于該課程的講解 一、函數(shù)式編程 1.1 函數(shù)式編程簡(jiǎn)...
    Gaolex閱讀 5,974評(píng)論 6 53
  • 2017年1月1日,新年第一天,小晴。 七點(diǎn)二十。照例鬧鐘叫醒,問(wèn)候早安。起床,洗漱,早餐,收拾,出門。 九點(diǎn)。準(zhǔn)...
    何夕何處何人閱讀 462評(píng)論 0 3

友情鏈接更多精彩內(nèi)容