2
$\begingroup$

I have two functions which calculate the same thing using different methods. Sometimes, the first method is much faster than the second method. Other times, the other way around. Just pretend this depends on a random coin-flip.

Can I evaluate both functions in parallel, and stop both evaluations as soon as one has finished?

Pseudo-code:

myMethod1[a_,b_]:=With[{p=Pause[RandomInteger[10]]},a+b]
myMethod2[a_,b_]:=With[{p=Pause[RandomInteger[10]]},a+b]
ParallelReturnFastest[{myMethod1[4,5],myMethod2[4,5]}]
$\endgroup$
0

2 Answers 2

2
$\begingroup$

What about ParallelTry? You could use it here as follows

myMethod1[a_, b_] := With[{p = Pause[RandomInteger[10]]}, Print["myMethod1"]; a + b]
myMethod2[a_, b_] := With[{p = Pause[RandomInteger[10]]}, Print["myMethod2"]; a + b]

ParallelTry[#[4, 5] &, {myMethod1, myMethod2}]
$\endgroup$
1
  • $\begingroup$ The description of ParallelTry is literally "evaluates $f_i$ in parallel, returning the first result received". So yes, thanks! $\endgroup$
    – LBogaardt
    Commented Jun 13, 2018 at 14:21
1
$\begingroup$

Did you try something like this?

ParallelSubmit[
 {
  a = AbsoluteTiming@Table[i, {i, 10000}][[1]]; Print[a];Abort[],
  a = AbsoluteTiming@Table[i, {i, 20000}][[1]]; Print[a];Abort[]
  }]

This will send the tasks to sub-kernels. Following evaluation of the

WaitAll[%]

will run your tasks and the output will be like:

{0.000252534, 1}, $Aborted

That is first kernel have stopped all the evaluation loop.

$\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.