🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
The sys.getsizeof function in Python's sys module returns the size of an object in bytes. This function is useful for memory profiling and optimizing the memory usage of your Python programs.
Table of Contents
- Introduction
sys.getsizeofFunction Syntax- Examples
- Basic Usage
- Checking Size of Various Data Types
- Handling Nested Objects
- Real-World Use Case
- Conclusion
Introduction
The sys.getsizeof function in Python's sys module provides the size of an object in bytes. This function is particularly useful for understanding the memory consumption of different objects and optimizing the memory usage of your programs.
sys.getsizeof Function Syntax
Here is how you use the sys.getsizeof function:
import sys
size = sys.getsizeof(object, default)
Parameters:
object: The object whose size you want to determine.default: An optional value to return if the object does not provide a size. If omitted, the function raises aTypeError.
Returns:
- The size of the object in bytes.
Examples
Basic Usage
Here is an example of how to use the sys.getsizeof function to get the size of an integer.
Example
import sys
# Getting the size of an integer
size = sys.getsizeof(42)
print(f"Size of 42: {size} bytes")
Output:
Size of 42: 28 bytes
Checking Size of Various Data Types
This example demonstrates how to check the size of various data types using sys.getsizeof.
Example
import sys
# Checking the size of various data types
int_size = sys.getsizeof(42)
str_size = sys.getsizeof("Hello, World!")
list_size = sys.getsizeof([1, 2, 3, 4, 5])
dict_size = sys.getsizeof({'a': 1, 'b': 2, 'c': 3})
print(f"Size of int: {int_size} bytes")
print(f"Size of str: {str_size} bytes")
print(f"Size of list: {list_size} bytes")
print(f"Size of dict: {dict_size} bytes")
Output:
Size of int: 28 bytes
Size of str: 62 bytes
Size of list: 96 bytes
Size of dict: 232 bytes
Handling Nested Objects
This example demonstrates how to handle nested objects using sys.getsizeof.
Example
import sys
# Defining a nested object
nested_list = [1, [2, [3, [4, [5]]]]]
# Function to recursively calculate the size of nested objects
def get_total_size(obj):
size = sys.getsizeof(obj)
if isinstance(obj, dict):
size += sum(get_total_size(v) for v in obj.values())
size += sum(get_total_size(k) for k in obj.keys())
elif isinstance(obj, list) or isinstance(obj, tuple) or isinstance(obj, set):
size += sum(get_total_size(i) for i in obj)
return size
# Calculating the total size of the nested object
total_size = get_total_size(nested_list)
print(f"Total size of nested_list: {total_size} bytes")
Output:
Total size of nested_list: 208 bytes
Real-World Use Case
Memory Profiling
In real-world applications, the sys.getsizeof function can be used to profile memory usage and optimize the memory footprint of your programs.
Example
import sys
# Function to profile memory usage of a list
def profile_memory_usage():
list_data = [i for i in range(1000)]
size = sys.getsizeof(list_data)
print(f"Memory usage of list_data: {size} bytes")
# Adding more elements to the list
list_data.extend(range(1000))
size = sys.getsizeof(list_data)
print(f"Memory usage of list_data after extending: {size} bytes")
# Example usage
profile_memory_usage()
Output:
Memory usage of list_data: 9112 bytes
Memory usage of list_data after extending: 9112 bytes
Conclusion
The sys.getsizeof function in Python's sys module returns the size of an object in bytes. This function is useful for memory profiling and optimizing the memory usage of your programs. Proper usage of this function can help you understand the memory consumption of different objects and improve the efficiency of your Python code by managing memory usage effectively.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment