Sunday, June 28, 2015

How to Find Memory Used in Computations

At some point you will need to — or just want to — push the limits of Mathematica and it may be helpful to measure memory consumed during a computation. Here are methods inspired by Wagon, Mathematica in Action (2nd ed., pp 431 et seq.). (See also Memory Management Tools.)

The first method is simple; store the initial MemoryInUse in a variable, do your calc, then subtract it from the current MemoryInUse.



Second, suppose you want to monitor memory in several places in your code. Initialize the variable currentMemory, then sprinkle


through your code like Print statements, and the enclosing Reap will cause each one to output the net memory consumed in bytes between the previous use and the current one. I say 'net' memory consumed because Mathematica is designed to optimize memory use and so clears memory in use every chance it gets. Following the pattern of Timing, I reverse the output to give the memory results first, then the function's output.

(*initialize s*); s=0;


Did you notice, as Wagon points out, that Do uses minimal memory during a calculation? It cleans up after every iteration.

Like Timing, this third method of checkMemory requires you to wrap your computation in checkMemory, access the result of your computation with First and if desired suppress the output with a semi-colon. Mimicking the structure of a built-in function is an example of a good programming technique. The designers of Mathematica are master programmers and they have created and debugged templates or paradigms of function structures. Often you can follow the structure of built-in functions to create sound ones of your own.

preComputationMemory=MemoryInUse[];Print["Memory in use at start is ",preComputationMemory];
Print["Memory in use at end is ",MemoryInUse[]];{memoryUsedInComputation,computation1}

Once it's done, this computation uses 32 bytes of memory and the result is 14.3927.


Memory in use at start is 31286024
Memory in use at end is 31286056

We find the memory use with the function output for a small Table.


Memory in use at start is 31289472
Memory in use at end is 31289752

Then suppress output, with a semi-colon as is done in Timing, for a large Table.


Memory in use at start is 31340688
Memory in use at end is 111344696

I left off the summation of the Table to show MemoryInUse during the calc. If we add Total, we see the max MemoryInUse reclaimed (-80,000,024 bytes).


Memory in use at start is 31359736
Memory in use at end is 31359864

Compare memory used in a Do loop. Pretty interesting!


Memory in use at start is 31364400
Memory in use at end is 31364432



So there you have it, Do takes 30 times as long as the functional command Table[...]//Total, but uses a minute fraction of the latter's memory.

No comments:

Post a Comment