2016-10-16 3 views
0

파이썬에서 이것을 코딩했습니다. 입력이 단지 40x40 인 경우 완료하는 데 너무 오래 걸렸습니다 (numpy을 사용한 이미지 처리 용). 그것의 행동은 다음과 같습니다 : 객체가있는 배열 (numpy 배열 인 'image'속성을 가짐)이 있습니다. 그런 다음 그 객체가 다른 배열의 어딘가에 있는지 확인한 다음 첫 번째 배열에서 다음 배열을 가져옵니다. 나는 모든 다른 배열에있는 경우 확인 때까지이 과정을 반복 :이 코드를 실행하는 데 시간이 오래 걸리는 이유는 무엇입니까? - Python

#__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 

내가 대신 내가 전에해야 할 무엇을 사용 4 for-loops의 단지 while으로 코딩 할 수 있었다. 왜 이렇게 오래 걸리지? 정상입니까, 아니면 잘못 되었나요? 복잡성은 x가 아닌 x로 가정합니다.

포함되지 않은 코드는 게터입니다. 처음에는 #notes으로 이해할 수 있기를 바랍니다.

THanks. 대신이의

+0

저는 'for'라고 생각하지 않고 'while'은 차이를 만듭니다. 'while' 문을 여기에있는 예제에 따라 미리 계산 된 값으로 바꾸고 시도해 볼 수 있습니까 : https://eval.in/661185 이것은 목록 길이를 다시 계산하지 않기 위해서입니다. 그게 얼마나 도움이되는지보십시오. – sal

+0

이전에 사용했던 것처럼 4 개의 중첩 루프 (for)를 사용하면 2D 배열 당 2 개의 루프를 사용하면 엄청난 차이가 있습니다. 복잡성은 x4가되고 잠시 동안 x가됩니다. – Wrong

+0

확인. 내가 제안한 것이 도움이 되었습니까? 'if not same' 다음에 줄에 적용해야합니다. – sal

답변

-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 

이 경우-지점 이전보다 덜 사용합니다.

+0

더 나은 스타일이지만 사소한 변화입니다. 이는 성과의 의미있는 요소가 아닙니다. 간단한 부울 검사를 미세 최적화하는 것은 코드의 가장 뜨거운 부분이 아닌 한 무의미합니다. – ShadowRanger

+0

나는 그것을 제거하는 것이 더 효율적이 될 것이라고 생각하지 않는다. 40+의 복잡성을 위해 오랜 시간이 걸리는 이유는 무엇입니까? – Wrong

관련 문제