當我們編寫大型腳本或多行代碼時,內存管理應該是我們的首要任務。因此,除了良好的編程知識外,我們還應該具備高效處理內存的良好知識。Python 中給出了許多函數來獲取程序中特定對象的內存大小,其中一個函數是 sizeof()。在本教程中,我們將學習 sizeof 函數及其在 Python 程序中的工作。
Python sizeof()函數
Python 中的 sizeof()函數並沒有準確地告訴我們對象的大小。它不返回生成器對象的大小,因為 Python 無法事先告訴我們生成器的大小。然而,實際上,它返回佔用內存的特定對象的內部大小(以位元組為單位)。
為了理解這一點,讓我們來看看下面的示常式序,它有一個無窮無盡的生成器對象。
示例 1: 看看下面的 Python 程序:
# A default function with endless generator object in it
def endlessGenerator():
# A counting variable to initialize the generator
counting = 0
# Using while loop to create an endless generator
while True:
yield counting
counting += 1 # Creating infinite loop
# Printing memory size of a generator object
print("Internal memory size of endless generator object: ", endlessGenerator.__sizeof__())
輸出
Internal memory size of endless generator object: 120
說明:
我們使用了一個默認函數,即 endlessGenerator(),在程序中創建了一個無窮無盡的生成器對象。在函數中,我們已經初始化了一個變數,即 counting = 0。我們在計數變數上使用了 While
循環,但沒有在循環上設置斷點。通過在函數中創建一個無限循環,我們將默認函數作為一個無限生成器對象。最後,我們使用 sizeof()函數列印了循環生成器對象的內存大小。
現在,我們可以清楚地了解 sizeof()函數的功能。由於上述程序中的無盡生成器對象沒有任何結束或斷點,Python 無法事先告訴我們生成器的大小。但與此同時,我們可以通過 sizeof()函數檢查分配給生成器對象的內部內存大小,因為它在 Python 中必須佔用一些內部內存。
讓我們再看一個例子,其中我們使用 sizeof()函數來獲取內部內存大小,而沒有任何開銷。
例 2:
# Define an empty list in the program
emptyList = []
# Printing size of empty list
print("Internal memory size of an empty list: ", emptyList.__sizeof__())
# Define some lists with elements
a = [24]
b = [24, 26, 31, 6]
c = [1, 2, 6, 5, 415, 9, 23, 29]
d = [4, 5, 12, 3, 2, 9, 20, 40, 32, 64]
# Printing internal memory size of lists
print("Memory size of first list: ", a.__sizeof__())
print("Memory size of second list: ", b.__sizeof__())
print("Memory size of third list: ", c.__sizeof__())
print("Memory size of fourth list: ", d.__sizeof__())
輸出
Internal memory size of an empty list: 40
Memory size of first list: 48
Memory size of second list: 104
Memory size of third list: 104
Memory size of fourth list: 136
說明:
使用 sizeof()函數,我們可以清楚地看到,一個空列表的內部內存大小是 40 位元組,列表中的每個元素都會將列表的總內存大小增加 8 位元組。
原創文章,作者:FEE8Y,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/127814.html