2

I'm struggling with speeding up my python code. I think that the main bottleneck of my code is located in the following function, where k is a counter, m is an empty matrix and image3 is a matrix that contains 0s and 1s. Do you have any suggestion? p.s I have already try to use Cython without much success, so I was wondering if there are some simpler way of solving the problem. Thank you in advance for help.

    def make_step(k,m,image3):
     
      for i in range(len(m)):
         
        for j in range(len(m[i])):
          if m[i][j] == k:
             
            if i>0 and m[i-1][j] == 0 and image3[i-1][j] == 0:   
              m[i-1][j] = k + 1  
              
               
            if j>0 and m[i][j-1] == 0 and image3[i][j-1] == 0:
              m[i][j-1] = k + 1  
              
             
            if i<len(m)-1 and m[i+1][j] == 0 and image3[i+1][j] == 0:
              m[i+1][j] = k + 1   
              
             
            if j<len(m[i])-1 and m[i][j+1] == 0 and image3[i][j+1] == 0:
              m[i][j+1] = k + 1   
    
Stuart
  • 9,597
  • 1
  • 21
  • 30
nicola
  • 29
  • 2
  • 3
    I’m voting to close this question because your code works but you are looking for a code review. Thus this question belongs on: https://codereview.stackexchange.com/ – Booboo Mar 10 '21 at 11:53
  • could you share the full example of how you change k variable outside of this function? – Singlet Mar 10 '21 at 13:36
  • are `m` and `image3` numpy matrices? or lists of lists? – Stuart Mar 10 '21 at 21:00
  • also, you say `m` is empty but do you mean it is initially a matrix of zeroes? And then progressively updated as `k` is increased? – Stuart Mar 10 '21 at 21:08
  • 1
    answers to [this question](https://stackoverflow.com/questions/52981880/accessing-neighboring-cells-for-numpy-array) may be helpful – Stuart Mar 10 '21 at 21:23
  • Thanks for your reply. m and image 3 are lists of lists indeed.As you said m is a matrix of zeros that is filled as k is increased – nicola Mar 11 '21 at 08:32

1 Answers1

1

I agree with Booboo, your code need review, and i suggest following approach:

Do a good benchmark to see where the time is spent. For these kind of problem perf_tool is a valid tool designed for this[*]. After you know where the code lack, you can rewrite the internal loop in vectorial using mask approach. This let you to reduce problem from O(n*m) to O(n)

[*] I'm the main developer of perf_tool

Glauco
  • 1,385
  • 2
  • 10
  • 20