如何提高python中for循环的性能

我正在用 python 进行大量模拟,模拟系统响应。


我目前一直在使用 Runge-Kutta 方案,但偶然发现了另一个我一直在测试的方案。


与我的 Runge-Kutta 相比,在 Matlab 中进行测试时,我获得了卓越的性能。但是,当我将其转移到 Python 时,速度明显变慢了。


我不确定这是否就是这样,或者我是否可以改进我的编码方式,所以如果可能的话,我很想听听您的一些意见。


Matlab中的代码,举例说明:


dt = 0.0001;

f = randn(1, (60 / dt));

ns = length(f);

yo = zeros(3,1);

P1 = [0; 0.001; 0];

F = [1 0.0001 0; 0.001 1 0.0001; 0.001 0 1];

y1 = zeros(3, ns);

tic

for i = 1:ns

    y1(:, i) = P1*f(:, i) + F*yo;

    yo = y1(:, i);

end

toc

其中循环在 0.55-0.61 秒内执行。


Python中的代码,举例说明:


dt = 0.0001

f = np.random.randn(1, int(60 / dt))

ns = np.size(f)

yo = np.zeros((3))

F = np.array([[1, 0.0001, 0], [0.001, 1, 0.0001], [0.001, 0, 1]])

P1 = np.transpose(np.array([[0, 0.0001, 0]]))

y1 = np.zeros((3, ns), order='F')

start_time = time.time()

for i in range(ns-1):

    y1[:, i] = np.dot(P1, f[:, i]) + np.reshape(np.dot(F, yo), (3))

    yo = y1[: , i]

print("--- %s seconds ---" % (time.time() - start_time))

其中循环在 2.8 -3.1 秒内执行。


我可以做些什么来改善这一点吗?


感谢您考虑我的问题。


胡说叔叔
浏览 271回答 2
2回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python