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

temp=Table[Random[], {i,1,10000}];

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

  • 1
    $\begingroup$ How about ByteCount[temp]? $\endgroup$
    – Hans Olo
    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$ Jul 26, 2021 at 18:48

2 Answers 2


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

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

Or this:

SetAttributes[memoryused, HoldAll];
memoryused[code_] := Module[{m0, res},
   m0 = MemoryInUse[];
   res = code;
   {MemoryInUse[] - m0, res}

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

  • 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
    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$ 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$ Jul 26, 2021 at 19:39

Your Answer

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

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