当我调用sys.getsizeof(4)
时,它返回14
。假设这与 C 中的 sizeof()
相同,那么这个值高得令人无法接受。
我想像使用一个大的原始字节数组一样使用内存数组。由于相关项目中数组的大小,内存开销是最重要的。可移植性也是一个大问题,因此使用 C 或使用更奇特的库并不是最佳选择。
有没有办法强制 Python 对单个正符号字节列表或元组成员使用更少的内存,仅使用标准 Python 3?
最佳答案
考虑到 Python 对象至少必须有 a pointer to its type struct and a refcount,14 给我的印象相当低。 .
PyObject
All object types are extensions of this type. This is a type which contains the information Python needs to treat a pointer to an object as an object. In a normal “release” build, it contains only the object’s reference count and a pointer to the corresponding type object. Nothing is actually declared to be a PyObject, but every pointer to a Python object can be cast to a PyObject*. Access to the members must be done by using the macros Py_REFCNT and Py_TYPE.
每个 Python 对象都会有这种开销。降低开销/有效负载比的唯一方法是拥有更多的有效负载,例如数组(普通 Python 和 numpy)。
这里的技巧是,数组元素通常不是 Python 对象,因此它们可以省去引用计数和类型指针,并占用与底层 C 类型一样多的内存。
关于python - 如何限制用于存储整数的内存量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42755256/