3
$\begingroup$

In a previous question I asked how to speed up the performance for NDSolve for a single evaluation. With the help provided, the solution is much faster. Now, I'd like to run the same code in different cores simultaneously.

Here is the same code as before, except in a Module:

func[var_] := Module[{x = var},
  Print["Starting to evaluate with x = ", x];
  gamma = 176;
  alphag = 0.01;
  alphajConstant = 0.00603;
  p = {Cos[Pi/6], 0, Sin[Pi/6]};
  current[t_] := Simplify`PWToUnitStep@Piecewise[{{3, t <= x}, {(5 - 3)/(150 - x) (t - x) + 3, x < t < 150}, {5, t >= 150}}];
  Beff[t_] := {0, 0, 1.5 - 0.8*(m[t].{0, 0, 1})};
  cons[t_] := -gamma*Cross[m[t], Beff[t]];
  tGilbdamp[t_] := alphag*Cross[m[t], cons[t]];
  tSlondamp[t_] := 
  current[t]*alphajConstant*gamma*Cross[m[t], Cross[m[t], p]];
  equ= {m'[t] == cons[t] + tGilbdamp[t] + tSlondamp[t], m[0] == {0, 0, 1}};
  sol1 = NDSolve[equ, {m}, {t, 0, 200}, MaxSteps -> \[Infinity]];
  mm[t_] = m[t] /. sol1[[1]];
  Print[Plot[mm[t][[1]], {t, 0, 200}]];];

And here is my attempt to run it in parallel processes:

LaunchKernels[2]
ParallelEvaluate[func[50], Kernels[][[1]]]
ParallelEvaluate[func[100], Kernels[][[2]]]

As far as I can tell, these do not run simultaneously; they run sequentially. Also, looking at the performance monitor on my Window 10 machine, the different cores don't seem to be working separately. What am I doing wrong?

$\endgroup$
5
$\begingroup$

Mathematica evaluates each expression in turn. Your expressions first launch a kernel, then the first ParallelEvaluate expression is evaluated synchronously, and then the next is evaluated synchronously.

You may want to have a look at ParallelSubmit and the Concurrency language guide. This allows you to setup jobs that will run in parallel.

LaunchKernels[2];
DistributeDefinitions[func];
jobs = Table[ParallelSubmit[{n}, func[n]], {n, {50, 100}}]

Mathematica graphics

results = WaitAll[jobs]

Both jobs run in parallel on thier own kernel.

Mathematica graphics

And the results pop out when all is done.

Mathematica graphics

You may want to address all the variables leaking out of your module at some point as well. Also, you do not need Print and ; in the last line of your module. Plot[mm[t][[1]], {t, 0, 200}] will do just fine to return the plot. ; is not what you think it is. Read Understand that semicolon (;) is not a delimiter.

Hope this helps.

$\endgroup$
  • $\begingroup$ This works nicely; speeds things very much. Will using local variables in the module stop them from "leaking"? $\endgroup$ – axsvl77 Jan 25 '17 at 1:32
  • $\begingroup$ @axsvl77 That is correct. $\endgroup$ – Edmund Jan 25 '17 at 9:57

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.