0

I'm working on a C# project to find the euclidean distance between 2 points.

Right now I have 2 for loops like this:

 for (int i = 0; i < pregcount; i ++)
        {
            double dist_minima = double.MaxValue;

            for (int j = 0; j < poiscount; j ++)
            {

                double distancia_cuadratica = Math.Pow(pois[j, 0] - preg[i, 0], 2) + Math.Pow(pois[j, 1] - preg[i, 1], 2) + Math.Pow(pois[j, 2] - preg[i, 2], 2);

           }
}

preg and pois are array matrix of n elements (preg is 250 elements and pois is 900,000 elements Is there a way to make this faster? like a function in C# or a library that would just calculate the distance more quickly?

I take almost 2 minutes to complete the whole thing. The calculation inside the second loop is what takes all the time.

Matimont
  • 739
  • 3
  • 14
  • 33

1 Answers1

1

For starters, don't use Math.Pow.

Find x = pois[j, 0] - preg[i, 0]; etc.

Then distancia_cuadratica = x * x + y * y + z * z;

You also don't appear to be just finding the distance between two points - you appear to want to find the CLOSEST point from preg to your pois values. Is this correct? It may have an impact on the total algorithm we'll suggest to you.

Other than that, try to avoid declaring variables inside a tight loop, if you can. Prefer ++j to j++.

Do you really need double accuracy? If not, you may be able to switch to float and save some speed.

.Net languages are arguably not ideal for calculations like this. C++ may be a better choice. If you use C++ for instance there are vectorizing intrinsics you can use to do operations like this much more quickly. I used to use Intel Performance Primitives. Now you can use things like CUDA to do these calculations on the GPU.

You could try something new and experimental like CUDA Sharp, if you want to.

Matt Cruikshank
  • 2,932
  • 21
  • 24