# How can I use ParallelTable with ParallelSum effectively?

I have this expression (as an example) as a function of nc and nr (real one is more nasty)

F[x_, y_, z_,
r_] = (Sin[x] + Sin[y] - Sin[z] - Cos[z] + Cos[x] Sin[y] Cos[z])/
1000;
sumF[x_, y_, z_, r_, nc_, nr_] :=
ParallelSum[
8 (nc/(2 \[Pi]))^-3 1/nr F[x, y, z, r], {r, -8, -1, 1/
nr}, {x, -\[Pi], \[Pi], (2 \[Pi])/nc}, {y, -\[Pi], \[Pi], (
2 \[Pi])/nc}, {z, -\[Pi], \[Pi], (2 \[Pi])/nc}]


and I would like to evaluate it at fixed nc and different values of nr ,for simplicity, say nc=10 and nr runs from 5 to 30 with step 5 (real code it runs to 1000 or more). So simply, I am using Table for that but my question is how can I Parallelize this process and is that even possible? I tried ParallelTable instead of Table but it is more time expensive?!

Table[sumF[x,y,z,r,10,nr]//N,{nr,5,30,5}]//AbsoluteTiming
{9.81641,{1.72881,1.7048,1.6968,1.69279,1.69039,1.68879}}


and with ParallelTable

ParallelTable[sumF[x,y,z,r,10,nr]//N,{nr,5,30,5}]//AbsoluteTiming
{13.062,{1.72881,1.7048,1.6968,1.69279,1.69039,1.68879}}


If you do full numerical evaluation without parallel calculation, you gain a factor of nearly 100 in speed.

F[x_, y_, z_, r_] =
(Sin[x] + Sin[y] - Sin[z] - Cos[z] + Cos[x] Sin[y] Cos[z])/1000

su[x_, y_, z_, r_, nc_, nr_] :=
Sum[8 (nc/(2 \[Pi]))^-3 1/nr F[x, y, z, r], {r, -8, -1,
1/nr}, {x, -\[Pi], \[Pi], (2 \[Pi])/
nc}, {y, -\[Pi], \[Pi], (2 \[Pi])/
nc}, {z, -\[Pi], \[Pi], (2 \[Pi])/nc}]

Table[Evaluate[su[x, y, z, r, 10, nr] // N], {nr, 5, 30,
5}] // AbsoluteTiming

(*   {0.1405747, {1.72881, 1.7048, 1.6968, 1.69279, 1.69039, 1.68879}}   *)


Once you have started all kernels, do ParallelTable to gain another factor of 2 in speed.

ParallelTable[
Evaluate[su[x, y, z, r, 11, nr] // N], {nr,    5, 30,
5}] // AbsoluteTiming

(*   {0.0780765, {1.54578, 1.52431, 1.51715, 1.51357, 1.51143, 1.50999}}   *)


Edit

I noticed, the faster evaluation is due to preevaluation of the sum. Even analytical results come very fast.

ParallelTable[
Evaluate[su[x, y, z, r, 12, nr]], {nr, 5, 30, 5}] // AbsoluteTiming

(*   {0.0780754, {(169 \[Pi]^3)/3750, (11999 \[Pi]^3)/270000, (
8957 \[Pi]^3)/202500, (7943 \[Pi]^3)/180000, (3718 \[Pi]^3)/84375, (
35659 \[Pi]^3)/810000}}   *)

• Thanks a lot! I tried to apply it to my real problem but it did not work magically as here, may you please have a look at this? Aug 14, 2020 at 20:57