您是否完全确定数组的每个单元只占用 1 个字节,因为默认情况下它可能为单元分配 8 个字节。
我创建了 3 x 3 的小数组,它占用 72 个字节。
import numpy as np
a = np.array(np.mat('1, 2, 3; 4, 5, 6; 7, 8, 9'))
print(a.nbytes) # Use this .nbytes instead of sys.getsizeof
256 x 256 x 3 x 8 字节 = 1572864 B = 1.5 MB
1.5 MB x 40,000 = 60000 MB \约 58.6 GB
你说你至少有 4 万个,所以如果你有更多,std 正在使用一些内存来展平数组
(请参阅http://docs.scipy.org/doc/numpy-1.9.2/reference/generated/numpy.std.html,你会在这里登陆https://github.com/numpy/numpy/blob/master/numpy/core/_methods.py)你会耗尽内存。
解决方案非常简单:从这里强制字节类型 int8 或其他:http://docs.scipy.org/doc/numpy-1.9.2/user/basics.types.html
a = np.array(np.mat('1, 2, 3, ; 4, 5, 6; 7, 8, 9'), dtype=np.int8)
print(a.nbytes) # Only 9 Bytes
检查可用内存尝试pythonic方式(而不是htop):
import psutil
m = psutil.virtual_memory()
print(m.available)
附:请记住,array.nbytes 显示了仅由数组元素消耗的内存量,没有一些用于数组维护的辅助字节。