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代码
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)')
结果对比
将两者数据画到一起,方便对比。
结论:
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)')