python - 如何限制用于存储整数的内存量?

标签 python python-3.x memory integer byte

当我调用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/

相关文章:

python - 试图找出为什么我的页面加载时间太慢

python - 获取保存在文本文件中的具有相应时间戳和场景评分的场景变化帧

c - 大型 PnP 驱动程序缓冲区

python - 无法在我的脚本中运行循环

python - 计算文本文件中的单词

C存储分配器用法?

r - 为什么R中的逻辑( boolean 值)需要4个字节?

python - 如何在 Python 中使用 for 循环查找数组中的重复元素?

python - 如何使用修改后的索引来旋转 pandas 数据框?

python - 为什么总是显示 ImportError : No module named pydot when I have already installed the module through pip?