Reputation: 29
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
Upvotes: 2
Views: 80
Reputation: 1465
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
Upvotes: 1