[파이썬] `sys.getsizeof()`: 객체의 크기 반환

Python is a popular programming language known for its ease of use and versatility. One important aspect of programming is managing memory, especially when dealing with large datasets or complex objects. In Python, the sys.getsizeof() function can be used to retrieve the size of an object in memory. In this blog post, we will explore how to use sys.getsizeof() to determine the size of different objects in Python.

Understanding sys.getsizeof()

The sys.getsizeof() function is part of the sys module in Python, which provides a way to access system-specific parameters and functions. It returns the size of an object in bytes. This can be useful when you want to optimize memory usage or understand the memory footprint of your code.

Usage of sys.getsizeof()

To use sys.getsizeof(), you need to import the sys module first. Here’s an example of how to retrieve the size of an object:

import sys

my_list = [1, 2, 3, 4, 5]
size = sys.getsizeof(my_list)

print(f"Size of my_list: {size} bytes")

In the code above, we import the sys module and define a list my_list. Calling sys.getsizeof(my_list) will return the size of my_list in bytes. We then print the size using a formatted string.

Determining the size of different objects

The sys.getsizeof() function can be used to determine the size of various objects in Python, including integers, floats, lists, dictionaries, and custom classes. Here are a few examples:

Strings:

import sys

str_obj = "Hello, World!"
size = sys.getsizeof(str_obj)

print(f"Size of str_obj: {size} bytes")

Lists:

import sys

my_list = [1, 2, 3, 4, 5]
size = sys.getsizeof(my_list)

print(f"Size of my_list: {size} bytes")

Dictionaries:

import sys

my_dict = {"key1": 1, "key2": 2}
size = sys.getsizeof(my_dict)

print(f"Size of my_dict: {size} bytes")

Custom classes:

import sys

class MyClass:
    def __init__(self, name):
        self.name = name

    def __sizeof__(self):
        return sys.getsizeof(self.name)

obj = MyClass("Example")
size = sys.getsizeof(obj)

print(f"Size of obj: {size} bytes")

By using sys.getsizeof(), you can analyze the memory usage of different objects and identify any potential space optimizations.

Conclusion

In this blog post, we explored the sys.getsizeof() function in Python and how to use it to determine the size of different objects. Understanding the memory footprint of your code can help you optimize memory usage and improve the performance of your Python programs.