Correct way to cap Mathematica memory use?

心不动则不痛 提交于 2019-11-27 05:22:44

问题


Under a 32-bit operating system, where maximum memory allocated to any one program is limited, Mathematica gracefully terminates the kernel and returns a max memory allocation error.

On a 64-bit OS however, Mathematica will freely use all the memory available and grind the system to a halt. Therefore, what is the correct way to cap memory usage? One could use MemoryConstrained combined with $Pre or CellEvaluationFunction but I would rather not tie up either of those for this purpose, or have to modify existing uses to incorporate this function.

Is there another way to globally restrict memory usage, such as a kernel flag, or system $Option?


回答1:


In Mathematica 8 you could start a memory watchdog, something along the lines of:

maxMemAllowed        = 15449604;
intervalBetweenTests = 1; (*seconds*)
iAmAliveSignal       = 0;
Dynamic[iAmAliveSignal]
RunScheduledTask[
       If[MemoryInUse[] > maxMemAllowed , Quit[], iAmAliveSignal++],      
       intervalBetweenTests];

Remember to run

RemoveScheduledTask[ScheduledTasks[]];

to disable it.

Edit

You may alert or interactively decide what to do before quitting. As requested, here is a trial with 1.3GB allocated. I can't go much further than that in this machine.

maxMemAllowed = 1.3 1024^3; (*1.3 GB*)
intervalBetweenTests = 1; (*Seconds*)
iAmAliveSignal = 0;
leyendToPrint = "";
Dynamic[leyendToPrint]
RunScheduledTask[
  If[MemoryInUse[] > maxMemAllowed, 
   CreateDialog[CancelButton["Max Mem Reached", DialogReturn[]]]; 
   Quit[],
   Print["Memory in use: ", MemoryInUse[]]; 
   leyendToPrint = 
    "Seconds elapsed = " <> ToString[iAmAliveSignal++]], 
  intervalBetweenTests];
IntegerPartitions[320, {15}];



来源:https://stackoverflow.com/questions/7854980/correct-way-to-cap-mathematica-memory-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!