假设我有一个类型为x
的大型矩阵numeric
,元素为1e4 * 1e4。
x
应该需要1e8 * 8 / 1e6 = 800MB内存(加上一些标头)。 object.size()
和pryr::object_size()
确认了这一点:
> x <- matrix(NA_real_, nrow = 1e4, ncol = 1e4)
> object.size(x)
800000216 bytes
> pryr::object_size(x)
800 MB
但是,“环境”标签中报告的大小为762.9MB。
RStudio 如何计算在 RStudio 的“环境”选项卡中报告的对象的内存使用情况,以及差异来自何处?
答案 0 :(得分:2)
RStudio向您显示与object.size
相同的内存大小。一个MB包含1024KB,一个KB包含1024B:
object.size(x)
# 800000216 bytes
object.size(x) / 1024 / 1024
# 762.9 bytes
我尝试查看pryr::object_size
代码,但它是用C实现的。我查看了source code,看起来字节的计算是这样的:
double bytes = 0;
// Big vectors always allocated in 8 byte chunks
if (n_bytes > 16) bytes = n_bytes * 8;
// For small vectors, round to sizes allocated in small vector pool
else if (n_bytes > 8) bytes = 128;
else if (n_bytes > 6) bytes = 64;
else if (n_bytes > 4) bytes = 48;
else if (n_bytes > 2) bytes = 32;
else if (n_bytes > 1) bytes = 16;
else if (n_bytes > 0) bytes = 8;
return bytes;
}
因此,这可能就是您计算与pryr匹配的800MB的原因。