我有一个复杂的有限差分模型,它用python编写,使用与下面示例代码相同的一般结构。它有两个for循环,一个用于每个迭代,然后在每个迭代中为x数组的每个位置设置一个循环。目前,代码需要两段时间才能运行(可能是因为for循环)。是否有一种简单的技术来使用numpy删除第二个for循环?
下面是我所使用的一般结构的一个简单例子。
import numpy as np
def f(x,dt, i):
xn = (x[i-1]-x[i+1])/dt # a simple finite difference function
return xn
x = np.linspace(1,10,10) #create initial conditions with x[0] and x[-1] boundaries
dt = 10 #time step
iterations = 100 # number of iterations
for j in range(iterations):
for i in range(1,9): #length of x minus the boundaries
x[i] = f(x, dt, i) #return new value for x[i]有没有人对我如何提高效率有任何想法或评论?
谢谢,
罗宾
发布于 2018-05-19 02:50:47
首先,这种对结构的小小改变提高了大约15%的效率。如果可以进一步优化这段代码,我不会感到惊讶,但这很可能是函数内部的算法,也就是简化数组元素操作的一些方法。使用生成器也可能有帮助。
import numpy as np
import time
time0 = time.time()
def fd(x, dt, n): # x is an array, n is the order of central diff
for i in range(len(x)-(n+1)):
x[i+1] = (x[i]-x[i+2])/dt # a simple finite difference function
return x
x = np.linspace(1, 10, 10) # create initial conditions with x[0] and x[-1] boundaries
dt = 10 # time step
iterations = 1000000 # number of iterations
for __ in range(iterations):
x = fd(x, dt, 1)
print(x)
print('time elapsed: ', time.time() - time0)https://stackoverflow.com/questions/50420637
复制相似问题