Paitel
Paitel

Reputation: 13

How to improve performance of the following code in Python?

for i in range(N):
   for j in range(M):
      l2 = numpy.argmin(numpy.abs(s - dE[i,j]))
      A[l1,l2] = A[l1,l2] + (n[j]+1)*I[i,j]

Basically, what it does is to locate the value of dE[i,j] in an array of s, and add a corresponding value (n[j]+1)*I[i,j] to the location. Is there anyway to avoid the for loops?

Upvotes: 0

Views: 96

Answers (1)

Alex Huszagh
Alex Huszagh

Reputation: 14584

You could technically use for i, j in it.product(range(N), range(M)): do_something(), but honestly, the bottleneck is the argmin and the time complexity of the loop: you're in slow territory due to your algorithm's design. Think about finding ways to refactor, if possible, or write an extension in C if the performance is prohibitive and there is no way to refactor.

If the performance is not a bottleneck, YAGNI: You ain't gonna need it. Premature optimization is the root of all evil.

Upvotes: 1

Related Questions