# Can I automatically stop operation that is too slow?

I need to write code like this: Do operation 1, but if it takes more that 5 seconds then stop it and do operation 2. Is it possible to do this somehow without manual interruption?

-
You can try TimeConstrained. Example from help TimeConstrained[Do[i^2, {i, 1000000}], 1] will terminate computation if it takes more than one second. You can adjust the time as needed. – Nasser Jun 13 '14 at 19:32
Thank you, TimeConstrained is what I actually need – user15933 Jun 13 '14 at 21:40

You can use TimeConstrained for this. Here is an example

tMax = 1;  (*second*)
f1[n_Integer] := Do[i^2, {i, n}];
TimeConstrained[f1[10^7], tMax]
(* $Aborted *)  You can use CheckAbort to check which function timed out or not, since TimeConstrained generated $Aborted. Here is an example

tMax = 5;  (*second*)
f1[n_Integer] := Do[i^2, {i, n}];
n = {10^1, 10^6, 10^8};
CheckAbort[TimeConstrained[f1[#], 5], "timed out!"] & /@ n
(*  {Null, Null, $Aborted} *)  So the last one timed out, but not the first two. You can customize this more as needed. (I need to find why the message "timed out" did not show up, but will look at this soon) - It looks like CheckAbort doesnt see the interrupt caused by TimeConstrained (if you do Alt-. quick enough you get the CheckAbort expression .. ) – george2079 Jun 13 '14 at 20:16 @george2079 yes, something is strange with CheckAbort here. it should have returned the message. I posted a question on chat now about it. Not relevant to this answer, as one does not have to use it. But it is strange. – Nasser Jun 13 '14 at 20:19 @Nasser - just found a horrible solution: CheckAbort[TimeConstrained[f1[#], 5], ""] & /@ n /.$Aborted -> "timed out!" – eldo Jun 13 '14 at 21:15
@Nasser: CheckAbort[TimeConstrained[f1[#], 5, Abort[]], "timed out!"] & /@ n – ciao Jun 14 '14 at 0:37