为什么这段代码需要这么长时间才能执行python
我在Python上编写了这个代码。如果输入值仅为40x40(用于使用为什么这段代码需要这么长时间才能执行python,python,performance,loops,Python,Performance,Loops,我在Python上编写了这个代码。如果输入值仅为40x40(用于使用numpy)进行图像处理),则需要花费很长时间才能完成。其行为如下:有一个数组,其中包含对象(具有“image”属性,即numpy数组),然后我检查该对象是否位于另一个数组中,然后从第一个数组中选择下一个,并重复该过程,直到我检查所有对象是否都位于另一个数组中: #__sub_images is the array containing the objects to be compared #to_compare
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
#uuu sub_uimages是包含要比较的对象的数组
#to_compare_image是作为参数接收的图像,用于检查对象是否在其中。
#get_sub_images()只是从接收的数组中检索要查找的数组中的对象。
#get_image()是从对象检索属性的方法
相同=正确
行像素=40#问题大小
cols_像素=40#问题大小
i=0#行索引以移动包含必须检查的对象(如果存在)的数组
j=0#col index以移动包含必须检查的对象(如果存在)的数组
k=0#行索引以移动数组,如果对象存在,将在其中进行检查
l=0#col索引,用于移动数组,如果对象存在,将在其中进行检查
而i
我设法在编写代码时只使用了一个,
,而不是以前使用的4个循环。为什么还要花这么长时间?这是正常的还是有什么问题?复杂性应该是x而不是x⁴
未包含的代码只是getter,我希望您能在开始时通过#notes
理解它
谢谢。代替这个:
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分支。我不认为for
和而有什么区别。您是否可以尝试使用预先计算的值替换while
语句,如以下示例所示:这是为了避免重新计算列表长度。看看这有多大帮助。如果你像我以前一样使用4个嵌套循环(for),就会有很大的不同,每个2D数组2个循环。复杂性变成x⁴, 再过一会儿就好了。我的建议有帮助吗?如果不相同,则应应用于后面的行。我不知道你的意思,很难将其更改为预先计算的值,因为在正确填充这些值之前,存在多个类,我认为这不会改变任何内容,因为它们仍然是相同的值。从上面的代码中,我最好的猜测是,像到\u compare\u image.get\u sub\u images()
这样的操作可能需要很长时间。这些都在每个循环中运行。因此,如果您看看我在这里发布的示例(),您将这些检查的计算移到while
循环之外。出于同样的原因,如果语句不相同,则将to_compare_image.get_sub_images()[0])
替换为其计算值。虽然样式更好,但这是一个微不足道的更改;这不是绩效的一个有意义的组成部分。微优化一个简单的布尔检查是毫无意义的,除非它是代码中最热门的部分(事实并非如此)。我不认为仅仅删除if就可以提高效率。你知道为什么复杂度达到40+需要这么长时间吗?