即使可以从终端运行相同的命令,R system()也无法分配内存

Ros*_*ler 5 linux r

我有一个R system()函数的问题(用于从R内部运行OS命令),即使有很多R会话占用了超过可用RAM的一部分(在我的情况下,大约为75%),该问题才会出现可用的RAM(在我的情况下为〜15GB)和相同的OS命令可以从终端轻松同时运行。

系统信息:
64GB RAM PC(本地台式机,不是基于云的或群集的)
Ubuntu 18.04.1 LTS-x86_64-pc-linux-gnu(64位)
R版本3.5.2(直接执行,例如不通过docker执行)

本示例说明了该问题。数据帧的大小d需要调整为尽可能小,并且仍然会引发错误。这将取决于您有多少RAM以及同时运行的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
Run Code Online (Sandbox Code Playgroud)

调用gc()R表示R已从64 GB RAM中分配了约38GB并同时free -m在终端上运行(请参阅下文),表明OS认为有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:~$ 
Run Code Online (Sandbox Code Playgroud)

因此free -m不能在R内部运行,因为无法分配内存,但free -m可以在终端上同时运行,并且您认为15GB足以运行像这样的轻量级命令free -m

如果R内存使用率低于某个阈值,则free -m可以在R内部运行。

我猜想R正在尝试分配free -m比实际需要更多的内存,这取决于已分配的内存量。任何人都可以对这里发生的事情有所了解吗?

谢谢

Joh*_*unt 5

我遇到了这个。R运行fork来运行子进程,将35GB的映像暂时加倍,从而超过您拥有的64GB。如果它存在,它将接下来调用exec并退还被欺骗的内存。这不是fork / exec应该执行的方式(应该在写入时复制而没有额外的费用-但在这种情况下,它会这样做)。

看来这是众所周知的:派生您必须有足够的内存来潜在地复制页面(即使那没有发生)。我猜您可能没有足够的交换空间(似乎至少建议使用RAM大小)。以下是一些有关配置交换的说明(适用于ec2,但涵盖了Linux的使用):https : //aws.amazon.com/premiumsupport/knowledge-center/ec2-memory-swap-file/