Find out how much memory is being used by an object in Python
Last Updated :
13 Apr, 2023
In this article, we are going to see how to find out how much memory is being used by an object in Python. For this, we will use sys.getsizeof() function can be done to find the storage size of a particular object that occupies some space in the memory. This function returns the size of the object in bytes. It takes at most two arguments i.e Object itself.
Syntax: sys.getsizeof(object*)
Parameters: arg can be int, str, function, etc.
Returns: Size of the given object in bytes.
This function is versatile and can work with any data type and even a function. For this first sys module has to be imported and then the object in consideration is passed to the function. Given below are various implementations for different objects.
Example 1: Get the size of an integer.
Python3
import sys
var = 1
print (sys.getsizeof(var))
|
Output:
28
Time Complexity: O(1)
Auxiliary Space: O(1)
Example 2: Get the size of an decimal.
Python3
import sys
var = 1.2
print (sys.getsizeof(var))
|
Output:
24
Time Complexity: O(1)
Auxiliary Space: O(1)
Example 3: Get the size of an String.
Python3
import sys
var1 = ""
var2 = "gfg"
var3 = "Welcome to gfg"
print (sys.getsizeof(var1))
print (sys.getsizeof(var2))
print (sys.getsizeof(var3))
|
Output:
64
72
96
Time Complexity: O(n)
Auxiliary Space: O(1)
Example 4: Get the size of an List.
Python3
import sys
var1 = []
var2 = [ 1 ]
var3 = [ 1 , 2 , 3 , 4 ]
print (sys.getsizeof(var1))
print (sys.getsizeof(var2))
print (sys.getsizeof(var3))
|
Output:
64
72
96
Time Complexity: O(n)
Auxiliary Space: O(1)
Example 5: Get the size of an Set.
Python3
import sys
var1 = set ([])
var2 = set ([ 1 , 2 , 3 , 4 , 5 ])
print (sys.getsizeof(var1))
print (sys.getsizeof(var2))
|
Output:
224
736
Time Complexity: O(n)
Auxiliary Space: O(1)
Example 6: Get the size of an Dictionary.
Python3
import sys
var1 = { 'Apple' : 1 }
var2 = { 'Apple' : 1 , 'ball' : 2 , 'cat' : 3 ,
'dog' : 4 , 'egg' : 5 , 'frog' : 6 }
print (sys.getsizeof(var1))
print (sys.getsizeof(var2))
|
Output:
240
368
Time Complexity: O(n)
Auxiliary Space: O(1)
Example 7: Get the size of an Function.
Python3
import sys
def func():
pass
var = func
print (sys.getsizeof(var))
|
Output:
136
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...