7

Is it possible to know what percentage of total used RAM by MMA is used by individual variables? I want to know how the total used RAM is distributed among different variables. Bytecount gives the answer but I have to enter the name of each variable manually.

MOON
  • 3,864
  • 23
  • 49

1 Answers1

7

I guess you need something like this:

a = RandomReal[{0, 1}, {1000, 1000}];
b = RandomReal[{0, 1}, {10000, 10000}];
Column@Thread@{Names["Global`*"], ByteCount[#] & /@ ToExpression /@ Names["Global`*"]}
{"a", 8000152}
{"b", 800000152}

It will show you all user-defined expressions and some of components of Global context created by default.

Öskå
  • 8,587
  • 4
  • 30
  • 49
Rom38
  • 5,129
  • 13
  • 28
  • I use MMA 9. Executing the code returns nothing. I think this is because I set the notebook's context as Unique to this notebook – MOON Jan 05 '15 at 12:55
  • I've checked this namelly with MMA9. Did you run it on an empty kernel? Try to create any expression before.. – Rom38 Jan 05 '15 at 12:57
  • It works if the notebook's context is set to Global. If the context is unique to the notebook it won't work. – MOON Jan 05 '15 at 12:59
  • 1
    Yes, :) because the list of variables is taken from the Global context. You can replace the name of context to your current. Or use this Names[$Context<>"*"] as recommend Alexey Popkov in http://stackoverflow.com/questions/6166027/list-all-user-defined-variables-functions-in-a-notebook-in-mathematica – Rom38 Jan 05 '15 at 13:03
  • @Öskå Yes, you're right. I think without ToExpression it returns the memory used by the string not the actual variable. – MOON Jan 05 '15 at 13:13
  • It does not work with ToExpression :\ as I see

    P.S. I found the misprint, It works good

    – Rom38 Jan 05 '15 at 13:14
  • This works good for me:

    Table[{Names[$Context <> "*"], ByteCount[#] & /@ ToExpression /@ Names[$Context <> "*"]}, {i, 1,1}];

    – MOON Jan 05 '15 at 13:16
  • @Öskå. Alright.

    Then, I can use SortBy[Flatten[tt, 1]\[Transpose], Last] to get the used memory by increasing order. tt is the code in my last comment.

    – MOON Jan 05 '15 at 13:23
  • @Öskå. If I add the total amount of used RAM by the code I wrote, the result is not equal to MemoryInUse[]. Do you know why? – MOON Jan 05 '15 at 13:29
  • 1
    @yashar I guess the frontend takes memory too, plus many other services. See MemoryInUse[$FrontEnd] – Öskå Jan 05 '15 at 13:37
  • The ByteCount[#] & /@ ToExpression /@ Names[$Context <> "*"] shows some additional service expressions in case if you have dynamic output in your notebook. So, the total amount of used memory could be bigger than sum of user-defined expressions consumption. – Rom38 Jan 05 '15 at 13:47