lundi 20 janvier 2020

Speeding-up a script by avoiding unnecessary repeated calculations in a nested for-for-if loop

Let's assume there are ~10**2 circles of known positions and radii. Also, assume there are ~10**3 points of known positions. The distribution being completely random, we know that if we probe each circle, in principle, it can have more than 1 point in it.

The following piece of python code is intended to loop over circles first and then over points. The way it's written, for each circle, the inner loop will calculate extraneous lines repeatedly if one only aims to keep track of circles which have at least 1 point.

For example, if one circle happens to have 100 points in it, the innermost loop will be run 100 times. But, I need to avoid this by manipulating the code such that, the moment one point is found inside a circle, the loop stop checking that circle for the rest of points. This way, I would tremendously increase the speed of my code. However, I am not exactly sure how to do the trick.

# position_data and radius_data are the properties of the circles mentioned above
for circle_position, circle_radius in zip(position_data, radius_data): 

    #(x, y) are the coordinates of the points mentioned above
    for x, y in zip(vals1, vals2):   

        if (condition1 and condition2 and condition3):
            # do some stuff  (these are the stuff that I want to avoid due to repetition)

Aucun commentaire:

Enregistrer un commentaire