Get approximate memory size of a Python object in bytes. This uses sys.getsizeof recursively for nested structures.
(obj)
| 15 | |
| 16 | |
| 17 | def get_memory_size(obj): |
| 18 | """ |
| 19 | Get approximate memory size of a Python object in bytes. |
| 20 | This uses sys.getsizeof recursively for nested structures. |
| 21 | """ |
| 22 | import sys |
| 23 | from collections.abc import Mapping, Iterable |
| 24 | |
| 25 | seen = set() |
| 26 | |
| 27 | def sizeof(o): |
| 28 | if id(o) in seen: |
| 29 | return 0 |
| 30 | seen.add(id(o)) |
| 31 | |
| 32 | size = sys.getsizeof(o) |
| 33 | |
| 34 | if isinstance(o, Mapping): |
| 35 | size += sum(sizeof(k) + sizeof(v) for k, v in o.items()) |
| 36 | elif isinstance(o, Iterable) and not isinstance(o, (str, bytes, bytearray)): |
| 37 | size += sum(sizeof(item) for item in o) |
| 38 | |
| 39 | return size |
| 40 | |
| 41 | return sizeof(obj) |
| 42 | |
| 43 | |
| 44 | def format_size(size_bytes: int) -> str: |
no test coverage detected
searching dependent graphs…