Feb-05-2021, 02:15 AM
(This post was last modified: Feb-05-2021, 02:15 AM by PJLEMZ.
Edit Reason: Python optimization of for loops for performance. Want help to use numpy vectorization methods instead.
)
Hi all!
I've been having trouble with the run time of my code as it is taking too long. I imagine this is because I am using for loops which is what I'm used to in MATLAB where for loops seems to be quicker than in Python. I've been trying for a while to use NumPy vectorization methods to do this instead as I have read this is better in terms of efficiency. However, I seem to be having issues implementing this. I would very much appreciate any guidance on how to do this. If there are other methods you suggest to improve performance, do feel free to advise me.
The loop I am trying to do this on is:
In other words, I want to replace this for loop with some sort of NumPy vectorization function as this will improve run time performance. In particular, I think the inner 2 loops would benefit from this.
Any advice would be greatly appreciated!
Thank you!
I've been having trouble with the run time of my code as it is taking too long. I imagine this is because I am using for loops which is what I'm used to in MATLAB where for loops seems to be quicker than in Python. I've been trying for a while to use NumPy vectorization methods to do this instead as I have read this is better in terms of efficiency. However, I seem to be having issues implementing this. I would very much appreciate any guidance on how to do this. If there are other methods you suggest to improve performance, do feel free to advise me.

The loop I am trying to do this on is:
for i in range(100000): theta = theta_rec[:][i] A = np.zeros((50,50)) for k in range(50): for j in range(50): A[k,j] = math.sin(theta[j] - theta[k]) B = -1 * np.array(sum(A)) d_theta = 0.001*(5 + B) theta[(i+1),:] = theta_rec[i,:] + d_theta for m in range(50): D[(i+1),m] = theta_rec[(i+1),m]%(2.0*math.pi)where theta_rec is a 100001x50 array. As you can see this deeply nested for loop isn't good for runtime and is acting as a bottleneck in my code.
In other words, I want to replace this for loop with some sort of NumPy vectorization function as this will improve run time performance. In particular, I think the inner 2 loops would benefit from this.
Any advice would be greatly appreciated!
Thank you!