Why does this code take so long to be executed? - Python
<p>I coded this on Python. It took way too long to finish if the input were just 40x40 (it's for image processing using <code>numpy</code>). Its behavious is the following: there's an array with objects in it (which have an 'image' attribute which is a numpy array) and then I check if that object is somewhere in another array, and then take the next from the first array and repeat the process until I've checked if all are in the other array:</p>

<pre><code>    #__sub_images is the array containing the objects to be compared
    #to_compare_image is the image that is received as parameter to check if the objects are in there.
    #get_sub_images() is just to retrieve the objects from the array from the received array to find.
    #get_image() is the method that retrieves the attribute from the objects
    same = True
    rows_pixels = 40  #problem size
    cols_pixels = 40  #problem size
    i = 0  #row index to move the array containing the object that must be checked if exist
    j = 0  #col index to move the array containing the object that must be checked if exist
    k = 0  #row index to move the array where will be checked if the object exist
    l = 0  #col index to move the array where will be checked if the object exist

    while i &lt; len(self.__sub_images) and k &lt; len(to_compare_image.get_sub_images()) and l &lt; len(to_compare_image.get_sub_images()[0]):

            if not np.array_equal(self.__sub_images[i][j].get_image(), to_compare_image.get_sub_images()[k][l].get_image()):
                same = False
            else:
                same = True
                k = 0
                l = 0
                if j == len(self.__sub_images[0]) - 1:
                    j = 0
                    i += 1
                else:
                    j += 1

            if not same:
                if l == len(to_compare_image.get_sub_images()[0]) - 1:
                    l = 0
                    k += 1
                else:
                    l += 1
</code></pre>

<p>I managed to code it with just a <code>while</code>, instead of 4 <code>for-loops</code> which is what I used to do before. Why is it taking so long still? Is it normal or is there something wrong? The complexity is supposed to be x and not xâ´</p>

<p>The code that is not included are just getters, I hope you can understand it with the <code>#notes</code> at the begining.</p>

<p>THanks.</p>

<p>Instead of this:</p>

<pre><code>if not np.array_equal(self.__sub_images[i][j].get_image(), to_compare_image.get_sub_images()[k][l].get_image()):
    same = False
else:
    same = True
    #snip
if not same:
    #snip
</code></pre>

<p>You can do this:</p>

<pre><code>same=np.array_equal(self.__sub_images[i][j].get_image(), to_compare_image.get_sub_images()[k][l].get_image())
if same:
    #snip
else:
    #snip
</code></pre>

<p>This uses less if-branches than before.</p>

python performance loops