5
$\begingroup$

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

1 Answer 1

4
$\begingroup$

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 = Compile`GetElement[Rpoints, 1];
    y0 = Compile`GetElement[Rpoints, 2];
    
    xmin = x = x0 + Compile`GetElement[shifts, 1, 1];
    ymin = y = y0 + Compile`GetElement[shifts, 1, 2];
    min = x x + y y;
    
    Do[
     x = x0 + Compile`GetElement[shifts, j, 1];
     y = y0 + Compile`GetElement[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 = 
  Developer`ToPackedArray[
   Flatten[Table[i v1 + j v2, {i, -1, 0}, {j, -1, 0}], 1]];
 final = cf[Rpoints, shifts];
 ]

0.005717

$\endgroup$
2
  • $\begingroup$ Do you not need a C-compiler Mathematica can access to run that code? $\endgroup$
    – josh
    Aug 17, 2023 at 13:23
  • $\begingroup$ 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.) $\endgroup$ Aug 17, 2023 at 13:32

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.