淺談Python 對象記憶體佔用

來源:互聯網
上載者:User
一切皆是對象

在 Python 一切皆是對象,包括所有類型的常量與變數,整型,布爾型,甚至函數。 參見stackoverflow上的一個問題 Is everything an object in python like ruby

代碼中即可以驗證:

# everythin in python is object def fuction(): return print isinstance(True, object) print isinstance(0, object) print isinstance('a', object) print isinstance(fuction, object)

如何計算

Python 在 sys 模組中提供函數 getsizeof 來計算 Python 對象的大小。

sys.getsizeof(object[, default])以位元組(byte)為單位返回對象大小。 這個對象可以是任何類型的對象。 所以內建對象都能返回正確的結果 但不保證對第三方擴充有效,因為和具體實現相關。......getsizeof() 調用對象的 __sizeof__ 方法, 如果對象由垃圾收集器管理, 則會加上額外的垃圾收集器開銷。

當然,對象記憶體佔用與 Python 版本以及作業系統版本關係密切, 本文的代碼和測試結果都是基於 windows7 32位作業系統。

import sys print sys.version

2.7.2 (default, Jun 24 2011, 12:21:10) [MSC v.1500 32 bit (Intel)]

基本類型

•布爾型

print 'size of True: %d' % (sys.getsizeof(True)) print 'size of False: %d' % (sys.getsizeof(False))

輸出:

size of True: 12 size of False: 12

•整型

# normal integer print 'size of integer: %d' % (sys.getsizeof(1)) # long print 'size of long integer: %d' % (sys.getsizeof(1L)) print 'size of big long integer: %d' % (sys.getsizeof(100000L)) 輸出:

size of integer: 12x size of long integer 1L: 14 size of long integer 100000L: 16

可以看出整型佔用12位元組,長整型最少佔用14位元組,且佔用空間會隨著位元的增多而變大。 在2.x版本,如果整數型別的值超出sys.maxint,則自動會擴充為長整型。而 Python 3.0 之後,整型和長整型統一為一種類型。

•浮點型

print 'size of float: %d' % (sys.getsizeof(1.0))

輸出:

size of float: 16

浮點型佔用16個位元組。超過一定精度後會四捨五入。

參考如下代碼:

print 1.00000000003 print 1.000000000005

輸出:

1.00000000003 1.00000000001

•字串

# size of string type print '\r\n'.join(["size of string with %d chars: %d" % (len(elem), sys.getsizeof(elem)) for elem in ["", "a", "ab"]]) # size of unicode string print '\r\n'.join(["size of unicode string with %d chars: %d" % (len(elem), sys.getsizeof(elem)) for elem in [u"", u"a", u"ab"]])

輸出:

size of string with 0 chars: 21 size of string with 1 chars: 22 size of string with 2 chars: 23 size of unicode string with 0 chars: 26 size of unicode string with 1 chars: 28 size of unicode string with 2 chars: 30

普通Null 字元串佔21個位元組,每增加一個字元,多佔用1個位元組。Unicode字串最少佔用26個位元組,每增加一個字元,多佔用2個位元組。

集合類型

•列表

# size of list type print '\r\n'.join(["size of list with %d elements: %d" % (len(elem), sys.getsizeof(elem)) for elem in [[], [0], [0,2], [0,1,2]]])

輸出:

size of list with 0 elements: 36 size of list with 1 elements: 40 size of list with 2 elements: 44 size of list with 3 elements: 48

可見列表最少佔用36個位元組,每增加一個元素,增加4個位元組。但要注意,sys.getsizeof 函數並不計算容器類型的元素大小。比如:

print 'size of list with 3 integers %d' % (sys.getsizeof([0,1,2])) print 'size of list with 3 strings %d' % (sys.getsizeof(['0','1','2']))

輸出:

size of list with 3 integers 48 size of list with 3 strings 48

容器中儲存的應該是對元素的引用。如果要準確計算容器,可以參考recursive sizeof recipe 。使用其給出的 total_size 函數:

print 'total size of list with 3 integers %d' % (total_size([0,1,2])) print 'total size of list with 3 strings %d' % (total_size(['0','1','2']))

輸出為:

total size of list with 3 integers 84 total size of list with 3 strings 114

可以看出列表的空間佔用為 基本空間 36 + (對象引用 4 + 對象大小) * 元素個數。

另外還需注意如果聲明一個列表變數,則其會預先分配一些空間,以便添加元素時增加效率:

li = [] for i in range(0, 101): print 'list with %d integers size: %d, total_size: %d' % (i, getsizeof(li), total_size(li)) li.append(i)

•元組

基本與列表類似,但其最少佔用為28個位元組。

•字典

字典的情況相對複雜很多,具體當然要參考代碼 dictobject.c, 另外 NOTES ON OPTIMIZING DICTIONARIES 非常值得仔細閱讀。

基本情況可以參考[stackoverflow] 的問題 Python's underlying hash data structure for dictionaries 中的一些回答:

•字典最小擁有8個條目的空間(PyDict_MINSIZE);
•條目數小於50,000時,每次增長4倍;
•條目數大於50,000時,每次增長2倍;
•鍵的hash值緩衝在字典中,字典調整大小後不會重新計算;

每接近2/3時,字典會調整大小。

以上這篇淺談Python 對象記憶體佔用就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援指令碼之家。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.