【问题标题】:How to determine the size of all objects in the current workspace in R? (not in WIndows)如何确定R中当前工作区中所有对象的大小? (不在 Windows 中)
【发布时间】:2014-03-28 05:16:08
【问题描述】:

在 Windows only 中,可以使用memory.size() 来获取当前R 会话中的(对象)占用的内存总量。

还可以使用print( object.size( thing ), units='auto') 了解单个对象的大小,它表示特定数据帧/表占用了多少兆字节/千字节。

但是如何做到相当于print( object.size( ---workspace--- ))呢?

循环for (thing in ls()) print( object.size( thing ), units='auto' )会打印错误的输出,如:

64 bytes
72 bytes
88 bytes
88 bytes
64 bytes
64 bytes
64 bytes
64 bytes
64 bytes
64 bytes
64 bytes
64 bytes
64 bytes
64 bytes
72 bytes
88 bytes
64 bytes
64 bytes
64 bytes
64 bytes
64 bytes
64 bytes
64 bytes
64 bytes
64 bytes
64 bytes
64 bytes

这不是我的意思。

【问题讨论】:

  • 我用谷歌搜索过这个问题无数次。在这里发布答案,以便其他人找到它。我的回答只是对stackoverflow.com/a/10383199/563329 的改编,但搜索者可能不会使用将他们引向该 SO 问题的术语。

标签: linux r memory-management


【解决方案1】:

基于@sgibb 的答案,下面的函数计算任何环境的大小。与此处发布的其他解决方案一样,它不包括嵌套环境,例如 R6 类。

env.size <- function(env = globalenv()) {
  env_vars = ls(envir = env)
  if (length(env_vars) == 0) {
    bytes = 0
  } else if (length(env_vars) == 1) {
    bytes = object.size(get(env_vars, envir = env))
  } else {
    bytes = sum(sapply(env_vars, function(x) object.size(get(x, envir = env))))
  }
  class(bytes) = "object_size"
  bytes
}

例如:

# defaults to global environment
env.size()
# 219240 bytes

# another environment
my_env = new.env()
my_env$x = rnorm(10)
env.size(my_env)
# 176 bytes

【讨论】:

    【解决方案2】:

    这给出了格式良好的输出:

    size = 0
    for (x in ls() ){
        thisSize = object.size(get(x))
        size = size + thisSize
        message(x, " = ", appendLF = F); print(thisSize, units='auto')
    }
    message("total workspace is ",appendLF = F); print(size, units='auto')
    

    像这样:

    a = 3.7 Kb
    ACE1 = 244.3 Kb
    etc..
    zfact_o = 48 bytes
    
    total is 130.9 Mb
    

    【讨论】:

      【解决方案3】:

      要打印整个工作区的大小,您可以尝试以下功能:

      workspace.size <- function() {
        ws <- sum(sapply(ls(envir=globalenv()), function(x)object.size(get(x))))
        class(ws) <- "object_size"
        ws
      }
      
      workspace.size()
      # 35192 bytes
      

      【讨论】:

      • 请注意,这不等同于memory.size,并且会被低估。例如,在 vanilla 工作区中,这给了我大约 8000 个字节,而 memory.size 给了我大约 25MB。包括baseenv() 会更接近一点,但会略微超调。
      • ...我们应该注意到object.size()是对占用空间的粗略估计。如果全局环境中有 2 个共享​​>对象,它们将被计算两次...
      • 如果你有任何字符向量,就会有很多共享对象。
      • 查看我的回复以了解此通用版本。
      【解决方案4】:

      正确的做法是:

      for (thing in ls()) {
          print(
            object.size(
              get(thing)
              ),
            units='auto')
          }
      

      这只是略有不同,因为循环使用get 来指定它应该是对象本身的大小,而不是对象的名称被测量。

      【讨论】:

        猜你喜欢
        • 2012-03-16
        • 1970-01-01
        • 1970-01-01
        • 2018-03-14
        • 1970-01-01
        • 2011-11-04
        • 2010-10-30
        • 1970-01-01
        • 2012-05-10
        相关资源
        最近更新 更多