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.
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!
question from:
https://stackoverflow.com/questions/66051797/how-to-use-vectorization-instead-of-for-loop-to-improve-efficiency-in-python 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…