我对 R system()
函数(用于从 R 中运行 OS 命令)有一个问题,只有当 R session 使用超过可用 RAM 的一部分(可能是在我的情况下约为 75%),即使有足够的可用 RAM(在我的情况下约为 15GB)并且可以从终端轻松地同时运行相同的操作系统命令。
系统信息:
64GB RAM PC(本地桌面 PC,非基于云或集群)
Ubuntu 18.04.1 LTS - x86_64-pc-linux-gnu(64 位)
R 版本 3.5.2(直接执行,而不是例如通过 docker)
这个例子演示了这个问题。数据框 d
的大小需要调整到尽可能小并且仍然会引发错误。这将取决于您拥有多少 RAM 以及同时运行的其他内容。
ross@doppio:~$ R
R version 3.5.2 (2018-12-20) -- "Eggshell Igloo"
Copyright (C) 2018 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)
R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.
Natural language support but running in an English locale
R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.
Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.
> n <- 5e8
> d <- data.frame(
+ v0 = rep_len(1.0, n),
+ v1 = rep_len(1.0, n),
+ v2 = rep_len(1.0, n),
+ v3 = rep_len(1.0, n),
+ v4 = rep_len(1.0, n),
+ v5 = rep_len(1.0, n),
+ v6 = rep_len(1.0, n),
+ v7 = rep_len(1.0, n),
+ v8 = rep_len(1.0, n),
+ v9 = rep_len(1.0, n)
+ )
> dim(d)
[1] 500000000 10
> gc()
used (Mb) gc trigger (Mb) max used (Mb)
Ncells 260857 14.0 627920 33.6 421030 22.5
Vcells 5000537452 38151.1 6483359463 49464.2 5000559813 38151.3
> system("free -m", intern = FALSE)
Warning messages:
1: In system("free -m", intern = FALSE) :
system call failed: Cannot allocate memory
2: In system("free -m", intern = FALSE) : error in running command
对 gc()
的调用表明 R 已经从 64 GB RAM 中分配了 ~38GB 并同时在终端中运行 free -m
(见下文)表明操作系统认为有大约 16GB 的空闲空间。
ross@doppio:~$ free -m
total used free shared buff/cache available
Mem: 64345 44277 15904 461 4162 18896
Swap: 975 1 974
ross@doppio:~$
因此 free -m
不能从 R 中运行,因为无法分配内存,但是 free -m
可以同时从终端运行,你会认为 15GB 足以运行像 free -m
这样的轻量级命令。
如果 R 内存使用低于某个阈值,则可以从 R 中运行 free -m
。
我猜想 R 正在尝试为 free -m
分配一定数量的内存,这比实际需要的多,并且取决于已经分配的内存数量。任何人都可以阐明这里发生的事情吗?
谢谢
最佳答案
我遇到过这个。 R 运行 fork 以运行子进程,暂时将 35GB 图像加倍到超过您拥有的 64GB。如果它还活着,它接下来会调用 exec 并归还被欺骗的内存。这不是 fork/exec 应该采用的方式(它应该是写时复制而无需额外成本 - 但在这种情况下它以某种方式做到了这一点)。
看起来这可能是众所周知的:要进行 fork ,您必须有足够的内存来潜在地复制页面(即使这种情况不会发生)。我猜你可能没有足够的交换空间(似乎至少推荐 RAM 的大小)。这里有一些关于配置交换的说明(它适用于 ec2,但涵盖了 Linux 的使用):https://aws.amazon.com/premiumsupport/knowledge-center/ec2-memory-swap-file/
关于即使可以从终端运行相同的命令,R system() 也无法分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54034171/