1.python对象所占字节数
import sys
sys.getsizeof(object) #
python是一种动态语言,变量的内存分配机制也不同,不是int/char类型的变量就是固定的4字节/1字节。
比如,python3中int类型是长整型,是动态长度的,理论上支持无限大的数字。
import sys
a = 0 # 只有0 24字节
# 除了0
b = 999999999 # 1~9位 28字节
c = 999999999999999999 # 10~18位 32字节
d = 999999999999999999999999999 # 19~27位 36字节
e = 999999999999999999999999999999999999 # 28~36位 40字节
print(sys.getsizeof(a),sys.getsizeof(b), sys.getsizeof(c), sys.getsizeof(d), sys.getsizeof(e))
24 28 32 36 40
对于负数,结果一样,负号不计入int的位数(-99是两位),-c仍占32位
对于string类型:
s0 = ''
s1 = '1'
s2 = '12'
s3 = '123'
s4 = '1234'
print(sys.getsizeof(s0), sys.getsizeof(s1), sys.getsizeof(s2), sys.getsizeof(s3), sys.getsizeof(s4))
49 50 51 52 53
对于float类型:
import sys
a = 0.0
b = 0.999999999
c = 0.9999999999
d = 10.9999999999999999999
e = 10.9999999999999999999999999999
print(sys.getsizeof(a),sys.getsizeof(b), sys.getsizeof(c), sys.getsizeof(d), sys.getsizeof(e))
24 24 24 24 24
对于其他:
from sys import getsizeof
class A(object):
pass
class B:
pass
for x in (None, 1, 1.2, 'c', [], (), {}, set(), B, B(), A, A()):
print("{0:20s}\t{1:d}".format(type(x).__name__, sys.getsizeof(x)))
2. numpy.frombuffer((buffer, dtype=float, count=-1, offset=0))
功能:读入字节流并转化成一维np.ndarray
参数:
buffer:字节流形式
dtype:返回ndarray的数据类型,默认为float
count:返回元素个数,默认-1,表示全部返回
offset:从butter的第offer个元素开始返回,offer默认为0,从index为0处返回
python3以后,字节流和字符串完全分开,字节流的格式是字符串前面加小写b
s = 'abc' # 字符串
by = b'abc' # 字节流
1)dtype = ‘S1’
import numpy as np
s = b'hello worldworldworldworld'
l1 = np.frombuffer(s, dtype='S1', count=6, offset=6)
l2 = np.frombuffer(s, dtype='S2', count=6, offset=6)
l3 = np.frombuffer(s, dtype='S3', count=6, offset=6)
print(l1, ' ', '大小:{} '.format(l1.shape), '类型:{} '.format(type(l1)))
print(l2, ' ', '大小:{} '.format(l2.shape), '类型:{} '.format(type(l2)))
print(l3, ' ', '大小:{} '.format(l3.shape), '类型:{} '.format(type(l3)))
dtype = ‘Sn’ 表示每次返回n个字符的string类型的值
2)dtype = ‘float’
a = b'1234567812345678'
l4 = np.frombuffer(a)
print(l4, ' ', '大小:{} '.format(l4.shape), '类型:{} '.format(type(l4)))
[6.82132005e-38 6.82132005e-38] 大小:(2,) 类型:<class 'numpy.ndarray'>
字节流中8个字符对应一个numpy的float值