gpt4 book ai didi

python - numpy vs Matlab 速度 - arctan 和 power

转载 作者:太空宇宙 更新时间:2023-11-03 12:37:11 25 4
gpt4 key购买 nike

在 Python 和 Matlab 中,我编写了生成矩阵并使用索引函数填充它的代码。 Python代码的执行时间是Matlab代码执行时间的20倍左右。两个具有相同结果的函数是用 python 编写的,bWay() 基于 this answer

这是完整的 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

用 timeit.timeit 测量的 Python 执行时间:

aWay() - 6.34s
bWay() - 6.68s

用 tic 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 代码的性能吗?

最佳答案

我只关注 Python 部分以及如何对其进行优化(抱歉,从未使用过 MATLAB)。

如果我正确理解您的代码,您可以使用:

def fastway():
x, y = np.ogrid[:width, :height] # you may need to swap "x" and "y" here.
return np.arctan(np.hypot(centerX-x, centerY-y) / constPart)

这是矢量化的,应该非常快。

%timeit fastway()
# 289 ms ± 9.62 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit aWay()
# 28.2 s ± 243 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit bWay()
# 29.3 s ± 790 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

如果您想知道:np.hypot(x, y)(x**2 + y**2)**0.5 相同。它不一定更快但更短,并且在某些边缘情况下会提供更精确的结果。

此外,如果您需要对标量进行操作,则不应使用 NumPy 函数。 NumPy 函数的开销如此之高,以至于处理一个元素所花费的时间与处理一千个元素所花费的时间相同,请参见示例 my answer on the question "Performance in different vectorization method in numpy" .

关于python - numpy vs Matlab 速度 - arctan 和 power,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44294442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com