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 
6
  • 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: codereview.stackexchange.com Commented Mar 10, 2021 at 11:53
  • could you share the full example of how you change k variable outside of this function? Commented Mar 10, 2021 at 13:36
  • are m and image3 numpy matrices? or lists of lists? Commented Mar 10, 2021 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? Commented Mar 10, 2021 at 21:08
  • 1
    answers to this question may be helpful Commented Mar 10, 2021 at 21:23

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.