【问题标题】:How would one check the system memory available using R on a Windows machine?如何在 Windows 机器上使用 R 检查可用的系统内存?
【发布时间】:2015-03-03 13:09:05
【问题描述】:

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

【问题讨论】:

  • 我几乎可以肯定我之前回答过这个问题。
  • 我在整个 StackOverflow 上都看得很透彻,但没有找到任何答案。有很多解决方案显示 R 会话中的内存使用情况,但没有显示有关实际系统内存的信息。
  • 这个问题是非常特定于操作系统的。在 Linux 上,您可以调用 system() 或 pipe() 并相应地按摩 free() 的输出。
  • 我正在使用 Windows 机器,我会更新问题以反映这一点。
  • 嗯,您可能还可以查询其他命令行工具——但我对那个平台不太熟悉。在基于 Unix 的系统上,并行编程通常会更容易一些。

标签: r windows memory


【解决方案1】:

为了完整起见,我在上面 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")
  }
}

【讨论】:

  • 我认为对于命令free 的Linux 参数应该是--kilo 而不是-k。来自free --help--kilo show output in kilobytes-k, --kibi show output in kibibytes
【解决方案2】:

我将 LyzanderR 的答案包装在一个函数中,该函数以千字节(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")
  }
}

【讨论】:

    【解决方案3】:

    也许以下其中一项会有所帮助(我也在 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 并根据需要使用。

    【讨论】:

    • 这是完美的谢谢。我做了一些输出更改,让它以 GB 为单位返回可用内存。 as.numeric(gsub("\r","",gsub("FreePhysicalMemory=","",system('wmic OS get FreePhysicalMemory /Value',intern=TRUE)[3])))/1024/1024 [1] 2.90044
    • 酷!很高兴它有帮助:)
    猜你喜欢
    • 2011-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-30
    • 1970-01-01
    • 2011-09-12
    相关资源
    最近更新 更多