Python獲取對象所佔內存大小

Python獲取對象所佔內存大小方法:

  1. sys.getsizeof()
  2. 內置函數__sizeof__()

先上代碼看看結果

import sys

class A(object):
    pass
class B:
    pass


for x in (None, 1, 1.2, complex(1, 1), 'c', [], (), {}, set(), B, B(), A, A()):
    print("{0:10s}\t{1:d}".format(type(x).__name__, sys.getsizeof(x)))

print("-------------------------")

for x in (None, 1, 1.2, complex(1, 1), '', [], (), {}, set()):
    print("{0:10s}\t{1:d}".format(type(x).__name__, x.__sizeof__()))

代碼運行結果爲:

NoneType  	16
int       	28
float     	24
complex   	32
str       	50
list      	64
tuple     	48
dict      	288
set       	224
type      	1016
B         	56
type      	1016
A         	56
-------------------------
NoneType  	16
int       	28
float     	24
complex   	32
str       	49
list      	40
tuple     	24
dict      	264
set       	200

可以看出兩個方法所計算的對象內存略有不同,__sizeof__爲python對象自帶的方法,計算對象所佔內存,和c語言的sizeof()函數功能相似。

    def __sizeof__(self): # real signature unknown; restored from __doc__
        """
        __sizeof__() -> int
        size of object in memory, in bytes
        """
        return 0

返回值爲int,返回內存中對象的大小,以字節爲單位。

而sys.getsizeof()調用對象的__sizeof__方法,如果對象由垃圾收集器管理,則會增加額外的垃圾收集器開銷,所以set,dict,tuple,list是由垃圾收集管理器管理的?垃圾收集管理器佔24字節?。

def getsizeof(p_object, default): # real signature unknown; restored from __doc__
    """
    getsizeof(object, default) -> int
    
    Return the size of object in bytes.
    """
    return 0

參考鏈接:
python 獲取對象的佔用內存大小
sys.getsizeof

系統:Windows 7,64位
Python版本:3.5.4

文中如有不對請指教!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章