2
$\begingroup$

Let's say that I have a function f[i] that takes quite a while to evaluate (evaluation time is different for different i) and I'd like to have as many values of f[i] as possible, for i = 1, 2, 3, ..., but in a specified amount of time (say, one minute) I want to stop evaluation and return values for i = 1, ... iFeasible (there is no way to calculate iFeasible before full computation). Basically, what I want to achieve is:

TimedConstainedTable[expr, {i, imin, imax}, maxTime]

To simplify: "If evaluating Table[expr, {i, imin, imax}] takes more time than maxTime, detect it, and return Table[expr, {i, imin, iFeasible}] (but do not evaluate values of expr for i = imin, ..., iFeasible again; extract them somehow from interrupted evaluation)."

It is super easy to implement:

list = {}; TimeConstrained[Do[AppendTo[list, f[i]], {i, 10^6}], 60, list]

but also very inefficient. Any improvement would be great.

$\endgroup$
3
$\begingroup$

Construction like this may help you.

    res = Reap@TimeConstrained[
      Do[Sow[f[i]]; Pause[0.1], {i, 1, 30}],
      1(*here number of seconds*)
    ]
    (*{$Aborted, {{f[1], f[2], f[3], f[4], f[5], f[6], f[7], f[8], f[9], f[10]}}}*)

for extractoin result use res[[2,1]]

$\endgroup$
0
0
$\begingroup$

Thank you molekyla777 for your answer. :) I tried very similar construction with Reap/Sow, but it did not work for some odd reason. Thank you very much again.

It would be very convenient for me to have TimeConstrainedTable[...] function. Therefore i molded molekyla777's answer to this:

SetAttributes[TimeConstrainedTable, HoldAll];

TimeConstrainedTable[expr_, iter__, time_] := Reap[TimeConstrained[Do[Sow[expr], iter], time]][[2, 1]]

and it seems to work just like Table (as I intend). For some reason though, if we evaluate:

i=0;

TimeConstrainedTable[f[i,j], {i, 10^6}, {j,5, 10}, 0.001]

it works perfectly, but "i" in notebook, in TimeConstrainedTable line, stays black, which seems weird to me (Table makes "i" blueish). Is it something to worry about? Can I "make it blueish" (indicate it is a variable with special use)? ^.- Here's clarifying screenshot:

Clarification for black and blue variables

$\endgroup$
1
  • 1
    $\begingroup$ it probably would better to create an extra question for such a followup. But in this case I'm sure that you would create a duplicate as that has been answered before. You might search for SyntaxInformation. This should roughly do what you want: SyntaxInformation[TimeConstrainedTable] = {"LocalVariables" -> {"Table", {2, Infinity}},"ArgumentsPattern" -> {_, {_, _, _., _.} .., _}} $\endgroup$ – Albert Retey Jul 30 '14 at 19:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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