返回单位:字节
sys.getsizeof()
import sys
>>> sys.getsizeof('3') 38 >>> sys.getsizeof('32') 39 >>> sys.getsizeof('325') 40 >>> sys.getsizeof(325) 24 >>> sys.getsizeof(1) 24 >>> sys.getsizeof(10000003250) 24 >>> sys.getsizeof(1000000000000000) 24 >>> sys.getsizeof(1000000000000000090) 24 >>> sys.getsizeof(10000000000000000900) 36
可以看出字符串是比整形占用空间小的,且整形在一定范围内占用空间是一样的
对比
import timeit import sys def f(): a, b, c = 3,2,1 return sys.getsizeof(a * 100 + b * 10 + c) def g(): a, b, c = 3,2,1 return sys.getsizeof(str(a) + str(b) + str(c)) def f2(): a, b, c = 3,2,1 return a * 100 + b * 10 + c def g2(): a, b, c = 3,2,1 return str(a) + str(b) + str(c) print min(timeit.repeat(f2)) print min(timeit.repeat(g2)) print f() print g()
结果
0.296730041504 0.70504784584 24 40
可以看出f()无论是从速度还是从内存占用都完胜g()
字典
>>> a {1: 'a', 2: 'b'} >>> sys.getsizeof(a) 280 >>> a[4] = "askjdfjllllllllllllll" >>> a[5] = "askjdfjllllllllllllll" >>> a {1: 'a', 2: 'b', 4: 'askjdfjllllllllllllll', 5: 'askjdfjllllllllllllll'} >>> sys.getsizeof(a) 280 >>> sys.getsizeof(a[1]) 38 >>> for i in range(100): ... a[i] = "fq08888888888" * 20 ... >>> len(a) 100 >>> sys.getsizeof(a) 12568