I want to run an exhaustive search algorithm that will take several hours to finish, so I'd like to have it execute Print
statement periodically, showing the fraction of the search space covered and the best result found so far. E.g.
For[i = 1, i <= n, i++,
...
If[Mod[i, stride] == 0, Print[{N[i/n], bestsofar}]
];
This works OK if the number of updates is not too big. Otherwise, the voluminous print out begins to overwhelm the notebook, making it increasingly difficult to navigate through it. Closing the cell does not help here: it is opened automatically with each new print-out. (Also, when the cell remains open, the window will not necessarily auto-scroll to keep the latest print-out in view, so one needs to manually scroll to see it. No big deal; just a bit annoying.)
I'm looking for a way to have each new print-out overwrite the previous one "in place". With other programming environments, at least in Unix-like systems, one achieves this effect by prepending a carriage return character (ASCII 13, aka \r
) to the printed string, and omitting the newline character (ASCII 10, aka \n
) from the end of the string1. A single newline character may be eventually printed, before execution terminates.
The Print
command implicitly adds the newline at the end of the output, and I have not found a way to suppress this behavior.
Is there some other way to achieve the effect of updating a running cell's print-out in-place?
UPDATE: based on molekyla777's answer, I modified the code above to:
Monitor[For[i = 1, i <= n, i++,
...
Refresh[{N[i/n], bestsofar}, UpdateInterval -> 1, TrackedSymbols -> {}]
];
I added the Refresh
call to reduce the performance drain that would otherwise result from updating the N[i/n]
term, which changes with each iteration. It basically does what Mod[i, stride] == 0
did in the previous version.
1If the length of the output string is not monotonically increasing, it may also be necessary to right-pad the output string with enough spaces to "erase" the previous output.)
UpdateGUIAndTakeASecondToDoOtherStuffPlease[];
$\endgroup$