This is my first question here. I have to solve coupled first order ODE-s and find the maximum of a function which depends on the solution of the ODE. I have to do this calculation in large quantities, so I wrote a function to do the job, but quickly ran out of memory. I think, this might be a minimal working example:
$HistoryLength = 0;
ClearMemory := Module[{}, Unprotect[In, Out];
Clear[In, Out];
Protect[In, Out];
ClearSystemCache[];];
GetMemoryUse :=
UnitConvert[Quantity[MemoryInUse[], "Bytes"], "Megabytes"] // N;
RunDE[ini_] :=
NDSolve[{y'[x] == y[x] Cos[x + y[x]], y[0] == ini}, y, {x, 0, 10}]
sol = First@RunDE[1];
y2[x_] := y[x] /. sol
Dummy[ini_] := Module[{x0 = ini, result},
result = FindMaximum[{y2[x], 5 < x < 10}, {x, 8}];
result[[1]]
]
GetMemoryUse
data = Dummy[#] & /@ Range[5 10^2];
ClearMemory
Remove[data, sol]
GetMemoryUse
It takes 5-10 seconds to compile, and shows the memory usage before and after using a Module with FindMaximum in a cycle. As you can see, I have already played with HistoryLength and Clear[In, Out]; Protect[In, Out].
The problem seems to be with the interpolating function. When I fed an explicit function to FindMaximum, I found no memory leak.
How can this kind of memory leak resolved?
Cheers, Zoltan