我試圖找到一種記憶體有效的方式來將資料存盤在 python 變數中以便快速訪問和分析。我初始化了一個二維陣列numpy,然后通過以下方式找到它的記憶體使用情況(使用sys以便稍后與其他變數型別進行比較):
a = np.zeros((1000,1000), dtype=np.float32)
print('The size of the numpy array is {} bytes'.format(sys.getsizeof(a)))
回傳: The size of the numpy array is 4000112 bytes
我可以numpy使用以下 for 回圈將其移動到一維陣列的字典中:
b = {}
for ii in range(1000):
b[f'{ii}']=a[:,ii]
print('The size of the dictionary is {} bytes'.format(sys.getsizeof(b)))
回傳:The size of the dictionary is 36968 bytes. 即使我洗掉a并運行垃圾收集,字典大小仍然存在,因此b不能只是一個指向a.
為什么一維陣列的字典比 ndarray 中的相同陣列占用更少的記憶體?
uj5u.com熱心網友回復:
你的觀察有兩個基本錯誤。
您不能洗掉物件,只能洗掉參考。如果洗掉
a,則洗掉指標。當您洗掉所有指標時,垃圾收集器可能會在某個時候洗掉該物件sys.getsizeof只給出容器的大小。要獲得總大小,您需要遍歷元素并求和。
大小大致相同的演示:
b = {}
for ii in range(1000):
b[f'{ii}']=a[:,ii].copy()
sum(sys.getsizeof(e) for e in b.values())
# 4096000
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/355113.html
標籤:Python 麻木的 字典 内存管理 numpy-ndarray
上一篇:通過定義函式構建3D物件
