Human readable memory sizes in lobstr

I've been using the pryr library to report memory usage of objects.
Generally I need to collect both the raw numeric value in bytes, and also a "human readable" string of the size.

This used to work for me:

# Size of an object utilizing builtin R function
obj_size <- object.size(my_obj)
obj_size_raw <- as.numeric(obj_size) #  7806621952
obj_size_str <- format(obj_size, "auto") # '7.3 GiB'

# Size of an object using pryr
obj_size <- pryr::object_size(my_obj) 
obj_size_raw <- as.numeric(obj_size) # 7806620144
obj_size_str <- capture.output(obj_size) # '7,806,620,144 B'

# Total memory utilized using pryr
total_size <- pryr::mem_used()
total_size_raw <- as.numeric(total_size) # 8985272040
total_size_str <- capture.output(total_size) # '8.99 GB'

I'm not sure exactly since when or from which version, but the capture.output for the pryr's object size stopped returning human readable strings. For example, instead of returning 7.3 GiB, it returns now 7,806,620,144 B.

I've read in pryr's GitHub repository thath it was superseded by lobstr for the matters of object size comparison. So, I see that it has lobstr::obj_size() and lobstr::mem_used() functions, both returning an object of the class lobstr_bytes. I tried using capture.output, and format()base functions to create a "human readable" string from the lobstr_bytes objects, but it did not work.

What is the best way to create a "human readable" string for the lobstr_bytes objects?

1 Like

The {prettyunits} package provides a function to make bytes human readable! You could use it as follows:

lobstr::obj_size(mtcars) |>
  as.numeric() |>
#> [1] "7.21 kB"

Created on 2022-04-08 by the reprex package (v2.0.1)

You could even define a quick function for ease of use:

pretty_obj_size <- function(object) {
  size <- lobstr::obj_size(mtcars)
  pretty_size <- prettyunits::pretty_bytes(as.numeric(size))
  cat(paste0(pretty_size, "\n", collapse = "")) # if you need a string, remove this line

#> 7.21 kB

Created on 2022-04-08 by the reprex package (v2.0.1)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.