4
$\begingroup$

I have a defined function $F(x,y,z)$ and data of $(x,y)$ and would like to evaluate the sum of F over data and at different z values. Here is a minimal example:

F[x_, y_, z_] := Sin[x  y  z];
data = Flatten[Table[{x, y}, {x, -2, 2, 0.05}, {y, -2, 2, 0.05}], 1];
ParallelTable[
   Sum[F[data[[i, 1]], data[[i, 2]], z], {i, Length@data}], {z, 0, 10,
     0.01}]; // AbsoluteTiming
{11.4345, Null}    

I tried to compile to speed it up but did not get that much enhancement

Fc = Compile[{{x, _Real}, {y, _Real}, {z, _Real}}, Sin[x  y  z], 
   CompilationTarget -> "WVM"];
ParallelTable[
   Sum[Fc[data[[i, 1]], data[[i, 2]], z], {i, Length@data}], {z, 0, 
    10, 0.01}]; // AbsoluteTiming
{9.85097, Null}    

Is there still a way to increase the speed?

$\endgroup$

1 Answer 1

6
$\begingroup$

Unless you're doing really high-level evaluation that cannot be Compiled, forget about parallelization. For more info see

Why won't Parallelize speed up my code?

Then, based on the experience obtained from

Has this implementation of FDM touched the speed limit of Mathematica?

It's not hard to achieve the following:

F[x_, y_, z_] := Sin[x   y   z];
data = Flatten[Table[{x, y}, {x, -2, 2, 0.05}, {y, -2, 2, 0.05}], 1];

ref = ParallelTable[
    Sum[F[data[[i, 1]], data[[i, 2]], z], {i, Length@data}], {z, 0, 10, 
     0.01}]; // AbsoluteTiming
(* {12.0628, Null} *)

cf = 
   Hold@Compile[{{data, _Real, 2}}, 
        Table[Sum[F[data[[i, 1]], data[[i, 2]], z], {i, Length@data}], {z, 0, 10, 
          0.01}], CompilationTarget -> "C", RuntimeOptions -> "Speed"] /. 
      DownValues@F /. Part -> Compile`GetElement // ReleaseHold; // AbsoluteTiming
(* {0.655155, Null} *)

tst = cf@data; // AbsoluteTiming
(* {0.0694954, Null} *)

tst - ref // Abs // Max
(* 1.49214*10^-13 *)

Compiled with Clang compiler in Win10, corresponding setting is

$CCompiler = {"Compiler"->GenericCCompiler, 
"CompilerInstallation"->"C:\\progra~1\\LLVM",
"CompilerName"->"clang.exe",
"SystemCompileOptions"->"-Ofast"}
$\endgroup$

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.