3 回答
TA贡献1895条经验 获得超7个赞
sys
sys.getsizeof(object[, default])
:
返回对象的大小(以字节为单位)。对象可以是任何类型的对象。所有内置对象都将返回正确的结果,但对于第三方扩展来说,这并不一定成立,因为它是特定于实现的。
这个 default
参数允许定义一个值,如果对象类型不提供检索大小的方法并将导致 TypeError
.
getsizeof
调用对象的 __sizeof__
方法,如果对象由垃圾收集器管理,则添加额外的垃圾回收器开销。
>>> import sys>>> x = 2>>> sys.getsizeof(x)24>>> sys.getsizeof(sys.getsizeof)32>>> sys.getsizeof('this')38>>> sys.getsizeof('this also')48
sys.getsizeof
TA贡献1813条经验 获得超2个赞
如何确定Python中对象的大小?
更完整的答案
Empty Bytes type scaling notes 28 int +4 bytes about every 30 powers of 2 37 bytes +1 byte per additional byte 49 str +1-4 per additional character (depending on max width) 48 tuple +8 per additional item 64 list +8 for each additional 224 set 5th increases to 736; 21nd, 2272; 85th, 8416; 341, 32992 240 dict 6th increases to 368; 22nd, 1184; 43rd, 2280; 86th, 4704; 171st, 9320 136 func def does not include default args and other attrs 1056 class def no slots 56 class inst has a __dict__ attr, same scaling as dict above 888 class def with slots 16 __slots__ seems to store in mutable tuple-like structure first slot grows to 48, and so on.
__dict__
property
__dict__
.
guppy.hpy
sys.getsizeof
:
Bytes type empty + scaling notes 24 int NA 28 long NA 37 str + 1 byte per additional character 52 unicode + 4 bytes per additional character 56 tuple + 8 bytes per additional item 72 list + 32 for first, 8 for each additional 232 set sixth item increases to 744; 22nd, 2280; 86th, 8424 280 dict sixth item increases to 1048; 22nd, 3352; 86th, 12568 * 120 func def does not include default args and other attrs 64 class inst has a __dict__ attr, same scaling as dict above 16 __slots__ class with slots has no dict, seems to store in mutable tuple-like structure. 904 class def has a proxy __dict__ structure for class attrs 104 old class makes sense, less stuff, has real dict though.
更完整的函数
obj.__dict__
obj.__slots__
gc.get_referents
import sysfrom types import ModuleType, FunctionTypefrom gc import get_referents# Custom objects know their class.# Function objects seem to know way too much, including modules.# Exclude modules as well.BLACKLIST = type, ModuleType, FunctionTypedef getsize(obj): """sum size of object & members.""" if isinstance(obj, BLACKLIST): raise TypeError('getsize() does not take argument of type: '+ str(type(obj))) seen_ids = set() size = 0 objects = [obj] while objects: need_referents = [] for obj in objects: if not isinstance(obj, BLACKLIST) and id(obj) not in seen_ids: seen_ids.add(id(obj)) size += sys.getsizeof(obj) need_referents.append(obj) objects = get_referents(*need_referents) return size
gc.get_referents
id(key)
白色类型,递归访问者(旧实现)
import sysfrom numbers import Numberfrom collections import Set, Mapping, dequetry: # Python 2 zero_depth_bases = (basestring, Number, xrange, bytearray) iteritems = 'iteritems'except NameError: # Python 3 zero_depth_bases = (str, bytes, Number, range, bytearray) iteritems = 'items'def getsize(obj_0): """Recursively iterate to sum size of object & members.""" _seen_ids = set() def inner(obj): obj_id = id(obj) if obj_id in _seen_ids: return 0 _seen_ids.add(obj_id) size = sys.getsizeof(obj) if isinstance(obj, zero_depth_bases): pass # bypass remaining control flow and return elif isinstance(obj, (tuple, list, Set, deque)): size += sum(inner(i) for i in obj) elif isinstance(obj, Mapping) or hasattr(obj, iteritems): size += sum(inner(k) + inner(v) for k, v in getattr(obj, iteritems)()) # Check for custom object instances - may subclass above too if hasattr(obj, '__dict__'): size += inner(vars(obj)) if hasattr(obj, '__slots__'): # can have __slots__ with __dict__ size += sum(inner(getattr(obj, s)) for s in obj.__slots__ if hasattr(obj, s)) return size return inner(obj_0)
>>> getsize(['a', tuple('bcd'), Foo()])344>>> getsize(Foo())16>>> getsize(tuple('bcd'))194>>> getsize(['a', tuple('bcd'), Foo(), {'foo': 'bar', 'baz': 'bar'}])752>>> getsize({'foo': 'bar', 'baz': 'bar'})400>>> getsize({})280>>> getsize({'foo':'bar'})360>>> getsize('foo')40>>> class Bar():... def baz():... pass>>> getsize(Bar())352>>> getsize(Bar().__dict__)280>>> sys.getsizeof(Bar())72>>> getsi ze(Bar.__dict__)872>>> sys.getsizeof(Bar.__dict__)280
TA贡献1789条经验 获得超8个赞
getsizeof
from pylab import *from sys import getsizeof A = rand(10)B = rand(10000)
In [64]: getsizeof(A)Out[64]: 40In [65]: getsizeof(B)Out[65]: 40
In [66]: A.nbytesOut[66]: 80In [67]: B.nbytesOut[67]: 80000
添加回答
举报