Skip to main content
2 of 5
deleted 32 characters in body
Henrik Schumacher
  • 109.4k
  • 7
  • 186
  • 322

This is a further extension of @Henric's answer, a little bit too long for a comment.

When playing with Henric's great solution, I observed that the two settings Parallelization->True and Parallelization->False did not make the difference I hoped for. My parallel kernel configuration shows that automatically 4 local kernels will be launched, whereas the difference between two two settings was only a factor 1.5. So I tried to do the parallelization myself.

The next function is the function testTriangle of Henric, but with Parallelization set to False.

origininside=
  With[{Part=Compile`GetElement},
    Compile[{{tr, _Real,2}},
      Module[{s1, s2, s3},
        s1=Sign[tr[[2,1]]tr[[3,2]]-tr[[2,2]]tr[[3,1]]];
        s2=Sign[tr[[3,1]]tr[[1,2]]-tr[[3,2]]tr[[1,1]]];
        s3=Sign[tr[[1, 1]]tr[[2,2]]-tr[[1,2]]tr[[2,1]]];
        Boole[s1==s2==s3]],
      CompilationTarget->"C",
      Parallelization->False,
      RuntimeAttributes->{Listable}]
    ];

On my quadcore computer, I launch 8 kernels:

LaunchKernels[8];

I seem to remember that a C-compiled function is not immediately available in the subkernels, so I expected that now I had to do the compilation of the function origininside on each of the subkernels. Maybe that idea dates from a long time ago, maybe I am wrong, but I was pleasantly surprised to see that, having compiled the function in the main kernel, it is immediately avaible on the subkernels as well.

Therefore, with the following command I create and test 25,000,000 triangles:

nn=2500;
  N@Total[ParallelTable[
    Total[origininside @  With[{angles=RandomReal[2 Pi,{nn,3,1}]},
      Join[Cos[angles],Sin[angles],3]] ], {10000}]]/10000/nn // AbsoluteTiming

{0.770372, 0.250022}

Since this timing includes the time required for the construction of the triangles, this construction of the parallelization makes the computation about 2.5 times as fast.

Fred Simons
  • 10.2k
  • 19
  • 50