Python与Matlab的循环性能

时间:2019-06-28 02:38:55

标签: python matlab performance for-loop

在Python和Matlab上,代码的矢量化版本都相当快。但是,有时我必须使用(for)循环。在这些情况下,Python循环确实很慢。为什么这样呢?

在下面的代码中,很明显,矢量化版本正在类似地运行。但是Matlab中的for循环版本相当不错,而Python版本确实很慢。

Python代码

import numpy as np
import time

N = 10000000

a = np.random.random(N)
b = np.random.random(N)

#vectorized
start_time = time.time()
c = np.dot(a,b)
print(c)
print("--- %s msec ---" % (time.time() - start_time))

#non-vectorized
start_time = time.time()
c = 0
for ii in range(N):
    c = c + a[ii]*b[ii]
print(c)
print("--- %s msec ---" % (time.time() - start_time))

Matlab代码

N = 10000000;

a = rand(N, 1);
b = rand(N, 1);

tic
c = dot(a, b);
disp(c);
toc

tic
c = 0;
for ii = 1:N
 c = c + a(ii) * b(ii);
end
disp(c)
toc

Python输出:

2500596.6897313246
--- 0.008107662200927734 sec ---
2500596.689731018
--- 3.6871590614318848 sec ---

Matlab输出:

2.4997e+06
Elapsed time is 0.027503 seconds.

2.4997+06
Elapsed time is 0.032014 seconds.

虽然Python向量化版本略快,但for循环版本却非常慢。

有什么解决方法可以在Python中更快地循环吗?

1 个答案:

答案 0 :(得分:0)

与Java进行类似的循环比较HERE。在python和(优化的)python包中使用for循环的解释可能会很有见地。