我有一个很大的二进制文件,我想使用struct.unpack()进行读取和解压缩。该文件由许多行组成,每行2957字节长。我使用以下代码读取了文件:
with open("bin_file", "rb") as f:
line = f.read(2957)
我的问题是,为什么尺寸返回:
import sys
sys.getsizeof(line)
不等于2957(在我的情况下是2978)?
你误解是什么sys.getsizeof()
呢。它返回Python用于字符串对象的内存量,而不是行的长度。
Python字符串对象轨道引用计数,对象类型和其他元数据连同实际的字符,所以2978个字节是不一样的东西作为字符串长度。
请参阅stringobject.h
类型的定义:
typedef struct {
PyObject_VAR_HEAD
long ob_shash;
int ob_sstate;
char ob_sval[1];
/* Invariants:
* ob_sval contains space for 'ob_size+1' elements.
* ob_sval[ob_size] == 0.
* ob_shash is the hash of the string or -1 if not computed yet.
* ob_sstate != 0 iff the string object is in stringobject.c's
* 'interned' dictionary; in this case the two references
* from 'interned' to this object are *not counted* in ob_refcnt.
*/
} PyStringObject;
其中PyObject_VAR_HEAD
被定义在object.h
,其中标准ob_refcnt
,ob_type
并且ob_size
都被定义的字段。
因此,长度为2957的字符串需要2958个字节(字符串长度+空),剩下的20个字节将用于保存引用计数,类型指针,对象“大小”(此处为字符串长度),缓存的字符串哈希和实习状态标志。
其他对象类型将具有不同的内存占用,并且所使用的C类型的确切大小也因平台而异。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句