在Python和Matlab上,代码的矢量化版本都相当快。但是,有时我必须使用(for)循环。在这些情况下,Python循环确实很慢。为什么这样呢?
在下面的代码中,很明显,矢量化版本正在类似地运行。但是Matlab中的for循环版本相当不错,而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))
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
2500596.6897313246
--- 0.008107662200927734 sec ---
2500596.689731018
--- 3.6871590614318848 sec ---
2.4997e+06
Elapsed time is 0.027503 seconds.
2.4997+06
Elapsed time is 0.032014 seconds.
虽然Python向量化版本略快,但for循环版本却非常慢。
有什么解决方法可以在Python中更快地循环吗?