I have a bunch of triangles (200k) I need to calculate the normals of. Here are five of them below, each one with its vertices in CCW order.
tris = {{{99.1175,-156.51,158.},{-63.7411,-173.073,158.},{-62.,-173.,158.}},{{-62.,-173.,3.},{-62.,-173.,158.},{-63.7411,-173.073,158.}},{{62.,-173.,158.},{99.1175,-156.51,158.},{-62.,-173.,158.}},{{-62.,-173.,3.},{62.,-173.,158.},{-62.,-173.,158.}},{{-99.1175,-156.51,158.},{-65.4575,-173.287,158.},{-63.7411,-173.073,158.}}};
Their normals can be simply calculated with
Normalize@Cross[#[[2]] - #[[1]], #[[3]] - #[[1]]] & /@ tris;
I'd like to Compile such function, therefore I reworked everything in the form
func=Compile[
{ax,ay,az,bx,by,bz,cx,cy,cz},
{
(-az*by+ay*bz+az*cy-bz*cy-ay*cz+by*cz)/Sqrt[Abs[-ay*bx+ax*by+ay*cx-by*cx-ax*cy+bx*cy]^2+Abs[az*bx-ax*bz-az*cx+bz*cx+ax*cz-bx*cz]^2+Abs[-az*by+ay*bz+az*cy-bz*cy-ay*cz+by*cz]^2],
(az*bx-ax*bz-az*cx+bz*cx+ax*cz-bx*cz)/Sqrt[Abs[-ay*bx+ax*by+ay*cx-by*cx-ax*cy+bx*cy]^2+Abs[az*bx-ax*bz-az*cx+bz*cx+ax*cz-bx*cz]^2+Abs[-az*by+ay*bz+az*cy-bz*cy-ay*cz+by*cz]^2],
(-ay*bx+ax*by+ay*cx-by*cx-ax*cy+bx*cy)/Sqrt[Abs[-ay*bx+ax*by+ay*cx-by*cx-ax*cy+bx*cy]^2+Abs[az*bx-ax*bz-az*cx+bz*cx+ax*cz-bx*cz]^2+Abs[-az*by+ay*bz+az*cy-bz*cy-ay*cz+by*cz]^2]
}
];
and run
func[Sequence @@ Flatten @ #] & /@ tris;
The speed gain is considerable (9.9 vs 1.2 seconds!), but I'd like to go further, namely using the Listable property and the Parallelization option. How can I do that? If I understand correctly parallelizability is a consequence of listability, so I added RuntimeAttributes -> {Listable}, Parallelization -> True
at the end of func
. But, how should I call the function then?