Example of Python Implementation Calculating Object's Memory Size

  • 2021-07-13 05:38:40
  • OfStack

In this paper, an example is given to describe the memory size of Python to realize the calculation object. Share it for your reference, as follows:

1-like sys. getsizeof () does not display complex dictionaries.

View the contents of the class:


def dump(obj):
 for attr in dir(obj):#dir Displays all methods of the class 
  print(" obj.%s = %r" % (attr, getattr(obj, attr)))

Here, getsizeof of all objects is called recursively:


def get_size(obj, seen=None):
 # From https://goshippo.com/blog/measure-real-size-any-python-object/
 # Recursively finds size of objects
 size = sys.getsizeof(obj)
 if seen is None:
  seen = set()
 obj_id = id(obj)
 if obj_id in seen:
  return 0
# Important mark as seen *before* entering recursion to gracefully handle
 # self-referential objects
 seen.add(obj_id)
 if isinstance(obj, dict):
  size += sum([get_size(v, seen) for v in obj.values()])
  size += sum([get_size(k, seen) for k in obj.keys()])
 elif hasattr(obj, '__dict__'):
  size += get_size(obj.__dict__, seen)
 elif hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes, bytearray)):
  size += sum([get_size(i, seen) for i in obj])
 return size

More readers interested in Python can check the topics of this site: "Summary of Python Process and Thread Operation Skills", "Python Data Structure and Algorithm Tutorial", "Summary of Python Function Use Skills", "Summary of Python String Operation Skills", "Introduction and Advanced Classic Tutorial of Python" and "Summary of Python File and Directory Operation Skills"

I hope this article is helpful to everyone's Python programming.


Related articles: