def get_size(obj, seen=none):# from # recursively finds size of objectssize = sys.getsizeof(obj)if seen is none:seen = setobj_id = id(obj)if obj_id in seen:return 0# important mark as seen *before* entering recursion to gracefully handle# self-referential objectsseen.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
让我们试一试:
d1 = dataitem("alex", 42, "-")print ("get_size(d1):", get_size(d1))d2 = dataitem("boris", 24, "in the middle of nowhere")print ("get_size(d2):", get_size(d2))
data = for p in range(100000):data.append(dataitem("alex", 42, "middle of nowhere"))snapshot = tracemalloc.take_snapshottop_stats = snapshot.statistics('lineno')total = sum(stat.size for stat in top_stats)print("total allocated size: %.1f mb" % (total / (1024*1024)))
我们不使用__slots__占用内存16.8mb,使用时占用6.9mb。这个操作当然不是最好的,但是确实代码改变的最小的。(not 7 times of course, but it’s not bad at all, considering that the code change was minimal.)