Is there a way to check how much time and memory it takes for calculation in Mathematica 9? I have a code where it takes about 1-2 minutes before it shows the output. I want to print the exact time and memory that calculations take in my notebook. Thank you,
2 Answers
You may useMaxMemoryUsed
for memory and and TimeUsed
for time.
Quantity[TimeUsed[], "Seconds"];
memory = N@UnitConvert[Quantity[MaxMemoryUsed[Table[2.5^x, {x, 10^5}];], "Bytes"], "Megabytes"];
Quantity[TimeUsed[], "Seconds"];
time = Out[-1] - Out[-3];
{time, memory}
{3.797 s, 9.9479 MB}
You can also get some real-time feedback with Monitor
. However, some time is taken up displaying the dynamic result so this is only useful on long calculations where this additional time is negligible.
ClearAll[timeAndMemoryMonitor]
SetAttributes[timeAndMemoryMonitor, {HoldFirst}]
timeAndMemoryMonitor[series_] :=
DynamicModule[
{startTime = Quantity[TimeUsed[], "Seconds"],
startMemory = Quantity[MemoryInUse[], "Bytes"]},
series = {{Quantity[0, "Seconds"], Quantity[0, "Bytes"]}};
Dynamic[
AppendTo[
series,
{Quantity[TimeUsed[], "Seconds"] - startTime,
Quantity[MemoryInUse[], "Bytes"] - startMemory}];
Refresh[
ListLinePlot[series,
Mesh -> Full,
AxesLabel -> Automatic,
TargetUnits -> "Megabytes"],
UpdateInterval -> 2]
]
]
Then
Monitor[
Table[2.5^x, {x, 10^5}];,
timeAndMemoryMonitor[values]
]
and
Last@values
{15.765 s, 9897040 B}
Also, because the memory can decrease as the kernel dynamically manages it this method is not as robust as MaxMemoryUsed
.
Hope this helps.
Two suggestions.
- You can wrap your calculation in
Timing
which according to the overview of Time Measurement & Optimization in the Wolfram documentation gives the "CPU time to run a command within the Wolfram Language kernel", e.g.Timing[Select[Range[500000], PrimeQ]] // Short
- You can issue the
TimeUsed[]
function before and after your calculation.
-
$\begingroup$ Thank you, what are the units in TimeUsed[] I assume milliseconds, right? $\endgroup$– ErfApr 4, 2020 at 20:00
-
$\begingroup$ "TimeUsed[] gives the total number of seconds of CPU time used so far in the current Wolfram System session." $\endgroup$ Apr 8, 2020 at 2:02
x=1
just to get it to initialize, then measure resources needed for an intense calculation and then measure resources needed to repeat that exact same calculation then those numbers may be substantially different because the second time may be reusing some of the previous results without needing to recalculate some parts of that. $\endgroup$