# Is it possible to interrupt a computation and give partial results?

Is it possible to interrupt a computation and Mathematica shows the result obtained so far? Or alternatively the program starts a new computation (in my case very long lists) and the program ends after obtaining the first 1000 (or another number) of results. Or can we ask the program (after hours of computation), how long it is expected until the end of it?

• For your second case, say, end a computation after some number of steps, you could do something like: Do[Print[a]; If[a >= 5, Abort[]], {a, 1, 10}] (where I abort if a is equal or greater than 5 in this case, for your case it could be 1000, or whatever number of operations you need). However, if you already know how many steps you'd like beforehand (say, 1000), why not use Table[], Do[], or While[] from the beginning? – TumbiSapichu Jul 4 at 12:49

Note: this solution here works for your second case: "Or alternatively the program starts a new computation (in my case very long lists) and the program ends after obtaining the first 1000 (or another number) of results". For your first case (interrupting a computation) you can follow this instructions (depending if you use Windows/Mac and if you're in a notebook).

Suppose you generate a list of integers that grows by adding an element if a random real is above 0.2. Thus, you cannot know how long will it take for your list to have 1000 elements, but you could check its length every time it is updated, and stop it there.

For instance:

(*How many elements in your computation?*)
myDesiredLength = 1000;

(*What's the intitial state/length of your computation?*)
myList = {1};

(*Update your computation according to whatever process you do, using While,
so it stops when you reach your desired length*)

i = 1;
While[
Length[myList] <= myDesiredLength,
If[RandomReal[] > 0.2,
AppendTo[myList, myList[[-1]] + 1]];
i++] // AbsoluteTiming


I don't think in general you can ask a computer beforehand how much time some computation will take, or if it will ever finish (this is the famous Halting problem). You could do some estimates, but it also depends on your particular computation (as some calculations take linear time, others exponential time, etc), what else your computer is doing, etc, etc. So, I'd better recommend giving your program some condition to stop beforehand, whether by Table, Do, While, For, etc, (and use some conditionals if needed).

• Note also that you could use Dynamic[i] outside the main loop to display how many elements have been calculated while the While loop is running. – Michael Seifert Jul 4 at 14:00

Yes, but your problem is underspecified. Here is an example.

NestWhile[Join[#, Range[RandomInteger]] &, {}, Length[#] < 100 &]