为什么这段代码需要很长时间才能被执行? - Python

时间:2016-10-16 00:53:11

标签: python performance loops

我用Python编写了这个代码。如果输入仅为40x40(使用numpy进行图像处理),则需要花费太长时间才能完成。它的行为如下:有一个包含对象的数组(它有一个'image'属性,这是一个numpy数组)然后我检查该对象是否在另一个数组中的某个位置,然后从第一个数组中获取下一个重复这个过程,直到我检查了是否所有都在另一个数组中:

    #__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 < len(self.__sub_images) and k < len(to_compare_image.get_sub_images()) and l < 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

我设法用while代替它,而不是4 for-loops,这是我以前做过的。它为什么需要这么长时间?这是正常还是有问题?复杂性应该是x而不是x⁴

未包含的代码只是getter,我希望您可以在开头使用#notes来理解它。

感谢。

1 个答案:

答案 0 :(得分:-1)

而不是:

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

你可以这样做:

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

这比以前使用更少的if分支。