21

I know that the varinfo() function will give the size of all objects in memory. This can be quite slow to execute, and will at times fail on certain objects, making the whole function hang. Is there a way to get the size in memory of a specific object, similar to the sys.getsizeof() function in Python?

2 Answers 2

38

varinfo() accepts regular expressions to match object names, so you can use something like

x = rand(100, 100)
varinfo(r"x")

to get info on x. For the size in bytes use

Base.summarysize(x)

EDIT: Originally this answer recommended whos(), however as @Plankalkül mentions whos() has been renamed to varinfo(), the answer was updated accordingly.

2
  • 2
    This was renamed to varinfo() in Julia 1.0 Commented Sep 13, 2018 at 10:10
  • Does this work for nested lists, nested dictionaries etc.? Does it work for instances of user classes?
    – minseong
    Commented Mar 1, 2021 at 14:55
8

You can use the sizeof function:

help?> sizeof
search: sizeof

  sizeof(s::AbstractString)

  The number of bytes in string s.

  sizeof(T)

  Size, in bytes, of the canonical binary representation of the given DataType T, if any.

julia> x = rand(100, 100);

julia> sizeof(x)
80000
6
  • 3
    that was unexpected, x is neither a string or a type.
    – amrods
    Commented Feb 1, 2016 at 15:35
  • 2
    Yes unexpected indeed if one reads only the description, you could open a PR or issue to the docs, in order to add this if you want, I can't do it right now, but will try to do so some other time, should be fairly easy to do. Commented Feb 1, 2016 at 16:00
  • 1
    Perhaps it should read sizeof(x) \n Size, in bytes, of the canonical binary representation of the x object for this method sizeof(x) at essentials.jl:87 Commented Feb 1, 2016 at 16:02
  • 4
    It also appears that there are a number of object types that sizeof does not work for (I had tried it previously before asking the question, but should have mentioned it in my text). For instance, I have a sparse matrix stored as Data. From that, I get these two different results: Base.summarysize(Data) ## 483747752 ; sizeof(Data) ## 40 Commented Feb 1, 2016 at 16:36
  • 4
    @aireties sizeof gives the size of an object, while summarysize sums the size of an object as well as its fields recursively. Data contains some references to its fields which are not bit types, so sizeof only counts the pointer sizes, rather than the actually data size.
    – colinfang
    Commented Mar 2, 2016 at 11:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.