在 Python 中查詢物件使用的記憶體量


記憶體通常在計算機系統中設定為一系列二進位制數字或位。每個位元組都有一個唯一的記憶體位置,可用於讀取或寫入位元組的值。位元組用於儲存記憶體中的資料,可以解釋為字元、整數、浮點數或其他資料型別。您可以藉助 sys.getsizeof() 和 pympler 的 asizeof() 等工具來測量 Python 中的記憶體使用情況。

方法 1:使用 Getsizeof() 函式

此函式可確定物件或資料結構所需的記憶體量。要測量其記憶體大小的物件作為唯一引數提供。任何型別的物件,包括使用者定義的類和例項,都可以作為引數傳遞。

語法

sys.getsizeof(*objt_name*)

*objt_name* 可以接受任何物件 - 整數、字串、函式等。

該函式以位元組為單位返回給定物件的大小。

演算法

  • 匯入所需的 sys 模組。

  • 建立一個包含各種資料型別的字典,例如字串、整數、浮點數、列表和函式。

  • 建立一個函式,該函式以整數 n 作為輸入,並返回從 0 到 n-1 的整數列表。

  • 使用 sys.getsizeof() 查詢方法 create_nmbr_list 和 my_dictn 的大小。

  • 列印值。

時間複雜度 - O(1)

空間複雜度 - O(n),其中 n 是字典的大小。

以下示例說明了建立一個字典,其中包含列表和 lambda 函式以及其他資料型別。一個使用 getsizeof() 函式生成長整數列表的函式。

示例

import sys

# Define a dictionary with various data types
my_dictn = {
   "string": "Tutorials Point",
   "integer": 662,
   "float": 3.14,
   "list": [12, 22, 32, 42, 52],
   "function": lambda x: x ** 2
}

# Define a function that creates list of integers
def create_nmbr_list(n):
   return [i for i in range(n)]

# Measure the size of the dictionary and function using sys.getsizeof()
print("Size of dictionary using sys.getsizeof(): ", sys.getsizeof(my_dictn))
print("Size of function using sys.getsizeof(): ", sys.getsizeof(create_nmbr_list))

輸出

Size of dictionary using sys.getsizeof():  232
Size of function using sys.getsizeof():  144

注意 - 記憶體中專案的數量可能會因多種因素而異,包括其他程式或作業系統當前使用的記憶體量。

方法 2:使用 Asizeof( ) 函式

此函式由 Pympler 包提供,用於記憶體分析和最佳化。與內建的 getsizeof() 函式不同,asizeof() 會考慮目標物件引用的所有物件的記憶體使用情況。

語法

asizeof(*object_*)

*object_* 可以接受任何物件 - 整數、字串、函式、布林值等

該函式以位元組為單位返回給定物件及其引用的物件的大小。

演算法

  • 匯入所需的 pympler.asizeof() 模組。

  • 建立一個名為 my_dict2 的字典,其中包含不同資料型別。

  • 建立函式以生成整數列表。

  • 可以使用 asizeof 函式記錄 My_dict2 和 create_int_list 的大小。

  • 使用變數 dictn_size_pympler 和 fnct_size_pympler 列印 my_dict2 和 create_int_list 的大小。

時間複雜度 - O(1)

空間複雜度 - O(n),其中 n 是字典的大小。

以下程式說明了一個包含 lambda 函式和其他資料型別的字典,使用 asizeof 函式查詢物件使用的記憶體。

示例

from pympler.asizeof import asizeof

# Define a dictionary with various data types
my_dict2 = {
   "string": "Hello Viewers",
   "integer": 42,
   "float": 3.14,
   "list": [1, 2, 3, 4, 5],
   "set": {10, 20, 30, 40, 50},
   "boolean": True,
   "function": lambda x: x ** 2,
}

# Define a function that creates a large list of integers
def create_int_list(i):
   return [x for x in range(i)]

# Measure the size of the dictionary and function using pympler.asizeof()
dictn_size_pympler = asizeof(my_dict2)
fnct_size_pympler = asizeof(create_int_list)

# Print the results
print("Size of dictionary using pympler.asizeof: ", dictn_size_pympler)
print("Size of function using pympler.asizeof: ", fnct_size_pympler)

輸出

Size of dictionary using pympler.asizeof:  384
Size of function using pympler.asizeof:  152

結論

Sys.getsizeof() 僅返回專案本身的大小,而 asizeof() 返回物件及其引用的每個物件的大小。因此,asizeof() 可以更清楚地顯示物件的記憶體使用情況。

雖然 sys.getsizeof() 僅返回物件本身的大小,但 asizeof() 會返回程式已匯入和使用的每個模組的大小。根據使用的 Python 版本,sys.getsizeof() 的反應可能不同。

更新於: 2023-08-23

2K+ 閱讀量

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.