0
$\begingroup$

I have the following code:

Answer = Table[Undefined, {1048576}];
SetSharedVariable[Answer];

ParallelDo[(

  eq = getEx[i];
  (* Some calculation here with eq *)
  Answer[[i]] = Solve[eq][[1]];

), {i, 1048576}];

Export["my_list.csv", Answer]

What getEx[i] does is to return me with an expression that I need to solve.

I need to get all 1M differents equations and save it´s answers, they are all independet of each other, so I could use parallel programming to speed thing a lot.

My problem is that with a SharedVariable, each kernel always goes to the main one for evaluation, so this code is almost slower then using a simple Do[] instead of ParallelDo[]

I would like to know how could I make this run better? Since I am just writing into a SharedVariable but never reading from that during the parallel programing.

Thanks to all!

$\endgroup$
1
  • $\begingroup$ Thanks, I will have a look on that. I just started 2 days ago working with mathemathica. $\endgroup$
    – user5343
    Commented Apr 12, 2018 at 11:08

1 Answer 1

4
$\begingroup$

Why not just use ParallelTable and dispense with the shared variable altogether? Also, make sure that the definition of getEx gets distributed: if it lives in Global that shouldn't be a problem, but if it lives in a package it might.

LaunchKernels[];
DistributeDefinitions[getEx];
solutions = ParallelTable[
  Solve[getEx[i]][[1]]
  {i, 1048576}
];
CloseKernels[];
$\endgroup$
3
  • $\begingroup$ Thanks!! I will try that $\endgroup$
    – user5343
    Commented Apr 12, 2018 at 11:14
  • $\begingroup$ It worked perfectly!, Thanks! My simulation was taking something around 3h, now I got that in 10 minuts $\endgroup$
    – user5343
    Commented Apr 12, 2018 at 12:02
  • $\begingroup$ You're welcome. For future reference: in Mathematica you generally don't want to use Do loops to assemble lists. That's what Table and functions like Map (and their Parallel brothers) are for. $\endgroup$ Commented Apr 12, 2018 at 13:11

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.