Python获取对象所占内存大小方法:
- sys.getsizeof()
- 内置函数__sizeof__()
先上代码看看结果
import sys
class A(object):
pass
class B:
pass
for x in (None, 1, 1.2, complex(1, 1), 'c', [], (), {}, set(), B, B(), A, A()):
print("{0:10s}\t{1:d}".format(type(x).__name__, sys.getsizeof(x)))
print("-------------------------")
for x in (None, 1, 1.2, complex(1, 1), '', [], (), {}, set()):
print("{0:10s}\t{1:d}".format(type(x).__name__, x.__sizeof__()))
代码运行结果为:
NoneType 16
int 28
float 24
complex 32
str 50
list 64
tuple 48
dict 288
set 224
type 1016
B 56
type 1016
A 56
-------------------------
NoneType 16
int 28
float 24
complex 32
str 49
list 40
tuple 24
dict 264
set 200
可以看出两个方法所