如何在 Windows 机器上使用 R 检查可用的系统内存?

How would one check the system memory available using R on a Windows machine?

我正在运行多线程 R 程序,但由于主机系统内存不足而导致某些节点崩溃时遇到问题。有没有办法让每个节点在继续运行之前检查整个系统的可用内存? (机器正在运行 Windows Server 2012 R2)

也许以下其中一项会有所帮助(我也在 Windows Server 2012 R2 上):

也许这是最有用的:

> system('systeminfo')
#the output is too big to show but you can save into a list and choose the rows you want

或者只使用以下其中一种特定于内存的方法

> system('wmic MemoryChip get BankLabel, Capacity, MemoryType, TypeDetail, Speed')
BankLabel    Capacity    MemoryType  Speed  TypeDetail  
RAM slot #0  8589934592  2                  512         
RAM slot #1  4294967296  2                  512   

空闲可用内存:

> system('wmic OS get FreePhysicalMemory /Value')
FreePhysicalMemory=8044340

可用内存总量

> system('wmic OS get TotalVisibleMemorySize /Value')
TotalVisibleMemorySize=12582456

基本上,您甚至可以 运行 任何其他您想要的 cmd 命令,您知道它可以帮助您完成 system 功能。 R 将在屏幕上显示输出,然后您可以保存到 data.frame 并根据需要使用。

我将上面 LyzandeR 的回答包装在一个函数中,returns 以千字节(1024 字节)为单位的物理内存。测试于 windows 7.

get_free_ram <- function(){
  if(Sys.info()[["sysname"]] == "Windows"){
    x <- system2("wmic", args =  "OS get FreePhysicalMemory /Value", stdout = TRUE)
    x <- x[grepl("FreePhysicalMemory", x)]
    x <- gsub("FreePhysicalMemory=", "", x, fixed = TRUE)
    x <- gsub("\r", "", x, fixed = TRUE)
    as.integer(x)
  } else {
    stop("Only supported on Windows OS")
  }
}

为了完成,我在上面的 Stefan 回答中添加了对 Linux 的支持- 在 Ubuntu 16

上测试
getFreeMemoryKB <- function() {
  osName <- Sys.info()[["sysname"]]
  if (osName == "Windows") {
    x <- system2("wmic", args =  "OS get FreePhysicalMemory /Value", stdout = TRUE)
    x <- x[grepl("FreePhysicalMemory", x)]
    x <- gsub("FreePhysicalMemory=", "", x, fixed = TRUE)
    x <- gsub("\r", "", x, fixed = TRUE)
    return(as.integer(x))
  } else if (osName == 'Linux') {
    x <- system2('free', args='-k', stdout=TRUE)
    x <- strsplit(x[2], " +")[[1]][4]
    return(as.integer(x))
  } else {
    stop("Only supported on Windows and Linux")
  }
}