# Is it possible to improve the speed where parallelization is not efficient?

I tried to use Parallelize but did not boost the speed. how can improve the speed?

boundR[v1_, v2_, {x_, y_}] :=
MinimalBy[
Flatten[Table[{x, y} + i v1 + j v2, {i, -1, 0}, {j, -1, 0}], 1],
Norm][[1]];
getfinponts[v1_, v2_, nnc_] :=
Block[{final},
Rpoints =
Flatten[Table[{i/nnc, j/nnc} . {v1, v2} 1., {j, 0., nnc - 1}, {i,
0., nnc - 1}], 1];
final = boundR[v1, v2, #] & /@ Rpoints;
Return[final]]


for arbitrary vectors v1 = {-3.14, -1.81}; v2 = {-3.14, 1.81}, I am aiming for ncc=600, but for ncc=300 it takes 5.3 sec on my laptop Win64 MMA12.3.

getfinponts[v1, v2, 300]; // AbsoluteTiming


Not sure why MinimalBy is so slow. However, the following function speeds up things considerably:

cf = Compile[{{Rpoints, _Real, 1}, {shifts, _Real, 2}},
Block[{m, min, x0, x, xmin, y0, y, ymin, normSquared},
m = Length[shifts];

x0 = CompileGetElement[Rpoints, 1];
y0 = CompileGetElement[Rpoints, 2];

xmin = x = x0 + CompileGetElement[shifts, 1, 1];
ymin = y = y0 + CompileGetElement[shifts, 1, 2];
min = x x + y y;

Do[
x = x0 + CompileGetElement[shifts, j, 1];
y = y0 + CompileGetElement[shifts, j, 2];

normSquared = x x + y y;

If[normSquared < min,
min = normSquared;
xmin = x;
ymin = y;
];
, {j, 2, m}];

{xmin, ymin}
],
CompilationTarget -> "C",
RuntimeAttributes -> {Listable},
Parallelization -> True,
RuntimeOptions -> "Speed"
];


Now you can do:

nnc = 300;
v1 = {-3.14, -1.81};
v2 = {-3.14, 1.81};

First@AbsoluteTiming[
Rpoints = Tuples[Most[Subdivide[0., 1., nnc]], 2] . {v1 , v2};
shifts =
DeveloperToPackedArray[
Flatten[Table[i v1 + j v2, {i, -1, 0}, {j, -1, 0}], 1]];
final = cf[Rpoints, shifts];
]


0.005717

• Do you not need a C-compiler Mathematica can access to run that code?
– josh
Aug 17, 2023 at 13:23
• Yes, of course. You do. ( You can also change CompilationTarget -> "C" to CompilationTarget -> "WVM"` to use the Wolfram Virtual Machine, but that is typically not as fast.) Aug 17, 2023 at 13:32