搜尋
首頁後端開發Python教學淺談Python 物件記憶體佔用

一切皆是物件

在 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, obinstance('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)]<font color="#000000" face="NSimsun"></font>

基本型

•布林型

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 'rn'.join(["size of string with %d chars: %d" % (len(elem), sys.getsizeof(elem)) for elem in ["", "a" , "ab"]]) # size of unicode string print 'rn'.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 string with 0 chars: : 30

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

集合型

•列表

# size of list type print 'rn'.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 物件記憶體佔用就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
什麼是Python Switch語句?什麼是Python Switch語句?Apr 30, 2025 pm 02:08 PM

本文討論了版本3.10中介紹的Python的新“匹配”語句,該語句與其他語言相同。它增強了代碼的可讀性,並為傳統的if-elif-el提供了性能優勢

Python中有什麼例外組?Python中有什麼例外組?Apr 30, 2025 pm 02:07 PM

Python 3.11中的異常組允許同時處理多個異常,從而改善了並發方案和復雜操作中的錯誤管理。

Python中的功能註釋是什麼?Python中的功能註釋是什麼?Apr 30, 2025 pm 02:06 PM

Python中的功能註釋將元數據添加到函數中,以進行類型檢查,文檔和IDE支持。它們增強了代碼的可讀性,維護,並且在API開發,數據科學和圖書館創建中至關重要。

Python的單位測試是什麼?Python的單位測試是什麼?Apr 30, 2025 pm 02:05 PM

本文討論了Python中的單位測試,其好處以及如何有效編寫它們。它突出顯示了諸如UNITSEST和PYTEST之類的工具進行測試。

Python中的訪問說明符是什麼?Python中的訪問說明符是什麼?Apr 30, 2025 pm 02:03 PM

文章討論了Python中的訪問說明符,這些說明符使用命名慣例表明班級成員的可見性,而不是嚴格的執法。

Python中的__Init __()是什麼?自我如何在其中發揮作用?Python中的__Init __()是什麼?自我如何在其中發揮作用?Apr 30, 2025 pm 02:02 PM

文章討論了Python的\ _ \ _ Init \ _ \ _()方法和Self在初始化對象屬性中的作用。還涵蓋了其他類方法和繼承對\ _ \ _ Init \ _ \ _()的影響。

python中的@classmethod,@staticmethod和實例方法有什麼區別?python中的@classmethod,@staticmethod和實例方法有什麼區別?Apr 30, 2025 pm 02:01 PM

本文討論了python中@classmethod,@staticmethod和實例方法之間的差異,詳細介紹了它們的屬性,用例和好處。它說明瞭如何根據所需功能選擇正確的方法類型和DA

您如何將元素附加到Python數組?您如何將元素附加到Python數組?Apr 30, 2025 am 12:19 AM

Inpython,YouAppendElementStoAlistusingTheAppend()方法。 1)useappend()forsingleelements:my_list.append(4).2)useextend()orextend()或= formultiplelements:my_list.extend.extend(emote_list)ormy_list = [4,5,6] .3)useInsert()forspefificpositions:my_list.insert(1,5).beaware

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能