6
$\begingroup$

I would like to write something along the lines of:

While[(t=Timer[])<60 (*in seconds*),
...do stuff...
]

Unfortunately, I'm not aware of a timer object in Mathematica, that starts counting upon initialization. Is there a way to do something equivalent?

$\endgroup$
2
  • 2
    $\begingroup$ Maybe use TimeConstrained. $\endgroup$
    – march
    Commented Jul 13, 2017 at 16:27
  • $\begingroup$ Need to be careful if you mean CPU time or wall clock time. $\endgroup$
    – Nasser
    Commented Jul 13, 2017 at 18:45

2 Answers 2

11
$\begingroup$

You could do something like this:

tstart = SessionTime[];
While[(t = SessionTime[] - tstart) < 60, (* do stuff *)]
$\endgroup$
2
  • $\begingroup$ does SessionTime measure the same thing as TimeConstrained? I did not think they measure same time. From help on TimeConstrained it says takes account only of CPU time spent inside the main Wolfram Language kernel process While SessionTime says gives the total number of seconds of real time that have elapsed since the beginning of your Wolfram System session. Both work ofcourse, just wanted to point out that user should be aware of what time to use there. $\endgroup$
    – Nasser
    Commented Jul 13, 2017 at 18:44
  • 1
    $\begingroup$ @Nasser Note that in OP's code he uses a function called Timer. This function can obviously not be aware of how much CPU time is spent on the nested computation. The fact that OP assigned Timer to a variable also indicates that he wants to use the value inside the loop, this is also not possible with TimeConstrained. Finally, TimeConstrained will interrupt the loop when the time has run out, whereas the code as outlined by OP will let the current iteration finish. So I don't consider TimeConstrained to be a good answer to the question. $\endgroup$
    – C. E.
    Commented Jul 13, 2017 at 19:05
5
$\begingroup$

An example using TimeConstrained:

TimeConstrained[
  n = 1; While[n < 5, Print[n]; n++; Pause[1]],
  2 ,(*seconds*)
  Print["Time is up."]; $Failed
]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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