Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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?

share|improve this question
4  
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 at 19:32
    
Thank you, TimeConstrained is what I actually need –  user15933 Jun 13 at 21:40

1 Answer 1

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)

share|improve this answer
    
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 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 at 20:19
    
@Nasser - just found a horrible solution: CheckAbort[TimeConstrained[f1[#], 5], ""] & /@ n /. $Aborted -> "timed out!" –  eldo Jun 13 at 21:15
2  
@Nasser: CheckAbort[TimeConstrained[f1[#], 5, Abort[]], "timed out!"] & /@ n –  rasher Jun 14 at 0:37

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.