matlab vs python: 跑循环的速度对比

测试1

matlab代码

N = 20:25;
iters = 2.^N;
time = zeros(1,length(N));
a = 0.111;
b = 0.222;
for k = 1:length(N)
    r = 0;
    t1 = clock;    
    for i = 1:2^N(k)
        r = 0.5*a + 0.6*b;
    end
    t2 = clock;
    time(k) = etime(t2,t1);    
end
plot(iters, time)
xlabel('iter')
ylabel('time(/s)')

python代码

N = range(20,26)
iters = [2**n for n in N]
ts = []
a, b = 0.111, 0.222
for n in N:    
    t1 = time.time()
    for i in range(2**n):
        r = 0.5*a + 0.6*b
    t2 = time.time()
    ts.append(t2-t1)
_, ax = plt.subplots()
ax.plot(iters, ts)
ax.set_xlabel('iter')
ax.set_ylabel('time(/s)')

结果对比
将两者数据画到一起,方便对比。
结论:随着循环增多,两者消耗时间都线性增大。对于这个测试案例(两个乘法和一个加法)。python约比matlab慢60倍
matlab vs python: 跑循环的速度对比_第1张图片

测试2

matlab代码

N = 20:25;
iters = 2.^N;
time = zeros(1,length(N));
a = 0.111;
b = 0.222;
M = [0.111,0.222;0.111,0.222];
for k = 1:length(N)
    r = 0;
    t1 = clock;    
    for i = 1:2^N(k)
        r = M(1,1)*a + M(1,2)*b;
    end
    t2 = clock;
    time(k) = etime(t2,t1);    
end
figure;
plot(iters, time)
xlabel('iter')
ylabel('time(/s)')

python代码

N = range(20,26)
iters = [2**n for n in N]
ts = []
M = np.array([[0.111, 0.222],[0.111, 0.222]])
a, b = 0.111, 0.222
for n in N:    
    t1 = time.time()
    for i in range(2**n):
        r = M[0,0]*a + M[0,1]*b
    t2 = time.time()
    ts.append(t2-t1)
_, ax = plt.subplots()
ax.plot(iters, ts)
ax.set_xlabel('iter')
ax.set_ylabel('time(/s)')

结果对比
将两者数据画到一起,方便对比。
结论:

  • 随着循环增多,两者消耗时间都线性增大。python约比matlab慢110倍
  • 将此测试结果与测试1对比, 可猜想:仅仅是在2*2矩阵中索引一个数,python也要比matlab很多倍,猜想慢110-60=50倍。再通过一个测试3来验证下猜想。
    matlab vs python: 跑循环的速度对比_第2张图片

测试3

matlab代码

N = 20:25;
iters = 2.^N;
time = zeros(1,length(N));
a = 0.111;
b = 0.222;
M = [0.111,0.222;0.111,0.222];
for k = 1:length(N)
    r = 0;
    t1 = clock;    
    for i = 1:2^N(k)
        r = M(1,1);
    end
    t2 = clock;
    time(k) = etime(t2,t1);    
end
figure;
plot(iters, time)
xlabel('iter')
ylabel('time(/s)')

python代码

N = range(20,26)
iters = [2**n for n in N]
ts = []
M = np.array([[0.111, 0.222],[0.111, 0.222]])
a, b = 0.111, 0.222
for n in N:    
    t1 = time.time()
    for i in range(2**n):
        r = M[0,0]
    t2 = time.time()
    ts.append(t2-t1)
_, ax = plt.subplots()
ax.plot(iters, ts)
ax.set_xlabel('iter')
ax.set_ylabel('time(/s)')

结果对比
猜想正确,仅仅是2*2矩阵索引一个数,python也比matlab慢50倍。
matlab vs python: 跑循环的速度对比_第3张图片

你可能感兴趣的:(python,matlab)