Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""
2@file
3@brief Functions to measure the size of an object.
4"""
6from sys import getsizeof
7from itertools import chain
8from collections import deque
11def object_size(o):
12 """
13 Calls `getsizeof <https://docs.python.org/3/library/sys.html#sys.getsizeof>`_.
15 @param o object
16 @return size of the object, that excludes references objects.
17 """
18 return getsizeof(o)
21def total_size(o, handlers=None):
22 """
23 Returns the approximate memory footprint an object and all of its contents.
25 @param o object to measure
26 @param handlers for recursivity purpose
27 @return total size
29 Automatically finds the contents of the following builtin containers and
30 their subclasses: tuple, list, deque, dict, set and frozenset.
31 To search other containers, add handlers to iterate over their contents:
33 ::
35 handlers = {SomeContainerClass: iter,
36 OtherContainerClass: OtherContainerClass.get_elements}
38 Source : `activestate <https://code.activestate.com/recipes/577504/>`_
39 referenced by function `getsizeof <https://docs.python.org/3/library/sys.html#sys.getsizeof>`_.
40 """
41 if handlers is None:
42 handlers = {}
44 def dict_handler(d):
45 return chain.from_iterable(d.items())
46 all_handlers = {tuple: iter, list: iter, deque: iter, dict: dict_handler,
47 set: iter, frozenset: iter}
48 all_handlers.update(handlers) # user handlers take precedence
49 seen = set() # track which object id's have already been seen
50 # estimate sizeof object without __sizeof__
51 default_size = getsizeof(0)
53 def sizeof(o):
54 if id(o) in seen: # do not double count the same object
55 return 0
56 seen.add(id(o))
57 s = getsizeof(o, default_size)
59 for typ, handler in all_handlers.items():
60 if isinstance(o, typ):
61 s += sum(map(sizeof, handler(o)))
62 break
63 return s
65 return sizeof(o)