0
$\begingroup$

Is there any way I can write a wrapper that wraps around a piece of code and evaluates how much memory has been used after the execution? Ideally I would like a function that performs the following operation

m0=MemoryinUse[];
temp=Table[Random[], {i,1,10000}];
output=MemoryinUse[]-m0

The code to be input in this function has to be arbitrarily long.

$\endgroup$
2
  • 1
    $\begingroup$ How about ByteCount[temp]? $\endgroup$
    – Hans Olo
    Commented Jul 26, 2021 at 18:40
  • $\begingroup$ It does the job but I would prefer to see some example code that's not an inbuilt Mathematica function. In my code I find situations like this all the time, and maybe the example is too trivial but learning how to write it from scratch would be cool $\endgroup$ Commented Jul 26, 2021 at 18:48

2 Answers 2

4
$\begingroup$

For a AbsoluteTiming sort of {value, result} output, maybe this:

memoryused = 
  Function[code, {MemoryInUse[] + #1, #2} &[-MemoryInUse[], code], 
   HoldAll];

Or this:

ClearAll[memoryused];
SetAttributes[memoryused, HoldAll];
memoryused[code_] := Module[{m0, res},
   m0 = MemoryInUse[];
   res = code;
   {MemoryInUse[] - m0, res}
   ];
$\endgroup$
0
$\begingroup$

I've found an answer to the question that doesn't require using the Mathematica inbuilt function ByteCount. The merit of this is that it takes two snapshots of the memory usage before the code is executed and after, which is a good way to evaluate background memory usage as well.

The idea is to take the code as a string input to the function and execute it within it. Here's a function that implements this

memoryused[string_]:=Module[{m0},
m0=MemoryInUse[];
ToExpression[string];
MemoryInUse[]-m0
];
$\endgroup$
3
  • 3
    $\begingroup$ I don't really understand what you mean by write it from scratch or not an inbuilt Mathematica function. In your answer, you are still using MemoryInUse[], which is a built-in Mathematica function ... $\endgroup$
    – Domen
    Commented Jul 26, 2021 at 19:01
  • $\begingroup$ Right! That was awkward phrasing. I had a specific goal in mind, that I edited in my answer. $\endgroup$ Commented Jul 26, 2021 at 19:08
  • 1
    $\begingroup$ No need for the side-effect of setting output to the difference, the last evaluation result is returned. $\endgroup$ Commented Jul 26, 2021 at 19:39

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.