为什么我的 Python 代码比我的 Matlab 代码慢 3 倍? (矩阵乘法和求逆)

问题描述 投票:0回答:1

我的 python 代码比我的 matlab 代码慢很多。

我的Python代码是:

import time 
from scipy import linalg
import numpy as np

N=1521
dt=0.1
thet=0.5
A0 = (np.linspace(1,N,N)).reshape(N,1)
A0 = np.repeat(A0,N,axis=1)
A1 = (np.linspace(1,N,N)).reshape(N,1)
A1 = np.repeat(A1,N,axis=1)
A2 = (np.linspace(1,N,N)).reshape(N,1)
A2 = np.repeat(A2,N,axis=1)
U = (np.linspace(1,N,N)).reshape(N,1)

start=time.time()
for t in range(19):
    u=U
    Y0 = (np.eye(N) + dt*(A0+A1+A2)) @ u
    Y1 = linalg.inv(np.eye(N) -thet * dt*A1 ) @ (Y0 -thet *dt*A1 @ u) 
    Y2 = linalg.inv(np.eye(N) -thet * dt*A2 ) @ (Y1 -thet *dt*A2 @ u) 
    U=Y2
print(time.time() - start)

output: 12.160803079605103

虽然我的 matlab 代码是:

clear all

N=1521;
dt=0.1;
thet=1;

A0=linspace(1,N,N)';
A0=repmat(A0,1,N);
A1=linspace(1,N,N)';
A1=repmat(A1,1,N);
A2=linspace(1,N,N)';
A2=repmat(A2,1,N);
U = linspace(1,N,N)';
I = eye(N);
tic;
for t=1:19
    u  = U;
    Y0 = (I + dt.*(A0+A1+A2))*u;
    Y1 = (I - thet.*dt.*A1) \ (Y0 - thet.*dt.*A1*u);
    Y2 = (I - thet.*dt.*A2) \ (Y1 - thet.*dt.*A2*u);
    U=Y2;
end
disp(toc)

output: 4.1449

我知道 matlab 在矩阵求逆方面会更快,但不会比 python 快 3 倍。我还看到两者的矩阵

U
不同,但无法发现差异。

我的Python代码中有什么明显的错误吗?

python performance matlab performance-testing matrix-inverse
1个回答
0
投票

在 python 循环中不断重新生成单位矩阵是否有原因?如果您只定义一次,就像在 MATLAB 中那样,您应该会加快速度。

© www.soinside.com 2019 - 2024. All rights reserved.