0

I want to get the memory usage of all lists in the current environment. data.table has tables that summarizes all tables in memory including size. Here's what I am using right now but I'm wondering if there's a better way to do it:

sapply(ls()[grepl("list",sapply(ls(), function(z) class(get(z))))], 
       function(z) format(object.size(get(z)), units = "Mb") )

I've seen Determining memory usage of objects? and Tricks to manage the available memory in an R session but they seem more about knowing usage of a specific item or managing memory, respectively. What I want is to get memory usage for all lists (this example) or all items that follow a certain naming convention. thanks!

Gautam
  • 2,597
  • 1
  • 28
  • 51

1 Answers1

2

One method would be to use eapply to search through all objects in the desired environment, check if each is a list and return the object.size if TRUE, else return NA.

eapply(as.environment(-1),
       FUN=function(x) if(is.list(x)) format(object.size(x), units = "Mb") else NA)
$a
[1] "7.2 Mb"

$b
[1] "72.5 Mb"

$f
[1] NA

The as.environment(-1) tells eapply to run over the environment that it was called from, which is the global environment here.

Also, ls.str might be useful here to return the str of list objects:

ls.str(mode = "list")
a : List of 2
 $ : int [1:1000000] 1 2 3 4 5 6 7 8 9 10 ...
 $ : int [1:899999] 2 3 4 5 6 7 8 9 10 11 ...
b : List of 2
 $ : int [1:10000000] 1 2 3 4 5 6 7 8 9 10 ...
 $ : int [1:8999999] 2 3 4 5 6 7 8 9 10 11 ...

data

#rm(list=ls())

f <- function() return(1)
a <- list(1:1e6, 2:9e5)
b <- list(1:1e7, 2:9e6)
lmo
  • 37,904
  • 9
  • 56
  • 69