在Python和Matlab中,我編寫了生成矩陣並使用索引函數填充它的代碼。 Python代碼的執行時間比Matlab代碼的執行時間長大約20倍。用同樣的結果有兩個函數都寫在Python中,bWay()
基於this answernumpy vs Matlab速度 - arctan和power
下面是完整的Python代碼:
import numpy as np
from timeit import timeit
height = 1080
width = 1920
heightCm = 30
distanceCm = 70
centerY = height/2 - 0.5;
centerX = width/2 - 0.5;
constPart = height * heightCm/distanceCm
def aWay():
M = np.empty([height, width], dtype=np.float64);
for y in xrange(height):
for x in xrange(width):
M[y, x] = np.arctan(pow((pow((centerX - x), 2) + pow((centerY - y), 2)), 0.5)/constPart)
def bWay():
M = np.frompyfunc(
lambda y, x: np.arctan(pow((pow((centerX - x), 2) + pow((centerY - y), 2)), 0.5)/constPart), 2, 1## Heading ##
).outer(
np.arange(height),
np.arange(width),
).astype(np.float64)
這裏是完整的Matlab代碼:
height = 1080;
width = 1920;
heightCm = 30;
distanceCm = 70;
centerY = height/2 + 0.5;
centerX = width/2 + 0.5;
constPart = height * heightCm/distanceCm;
M = zeros(height, width);
for y = 1 : height
for x = 1 : width
M(y, x) = atan(((centerX - x)^2 + (centerY - y)^2)^0.5/constPart);
end
end
Python的執行時間timeit.timeit:
aWay() - 6.34s
bWay() - 6.68s
抽動TOC測量Matlab的執行時間:
0.373s
爲了縮小範圍予測arctan
,平方和循環次
的Python:
>>> timeit('arctan(3)','from numpy import arctan', number = 1000000)
1.3365135641797679
>>> timeit('pow(3, 2)', number = 1000000)
0.11460829719908361
>>> timeit('power(3, 2)','from numpy import power', number = 1000000)
1.5427879383046275
>>> timeit('for x in xrange(10000000): pass', number = 1)
0.18364813832704385
Matlab的:
tic
for i = 1 : 1000000
atan(3);
end
toc
Elapsed time is 0.179802 seconds.
tic
for i = 1 : 1000000
3^2;
end
toc
Elapsed time is 0.044160 seconds.
tic
for x = 1:10000000
end
toc
Elapsed time is 0.034853 seconds.
在所有3種情況下,Python代碼執行時間延長了幾倍。
有什麼我可以做的,以改善這種python代碼的性能?
您不應該矢量化MATLAB和Python/NumPy代碼的性能嗎? – Divakar
比較次優(或差)解決方案的性能並不真正有趣和/或有用。請嘗試優化每個解決方案的性能,然後比較性能:) – MSeifert
謝謝,我會研究它,看看時間如何比較然後 – vbajcinovci