如何解决为什么pypy3比python慢
为了更快地运行我的代码,我认为 pypy 就是我的工作。但是,我发现我的某些代码实际上速度较慢。
有人能帮我理解为什么会这样吗?
这是我在functions.py的第663行确定的调用(加权总和),在pypy中较慢,pypy是类中的主要方法。
它被调用了 500000 次。
def __call__(self,verbose=False):
if len(self.links) != self.weights.size:
raise Exception(f'Number of links ...')
super().check_links(len(self.links))
inputs = np.array([link.get_value() for link in self.links])
self.value = np.dot(inputs,self.weights)
return super().__call__(verbose)
这是使用 cProfile 运行的 pypy 的蛇形视图
这是用python运行的snakeviz视图
编辑:20210612
@mattip 我采纳了你的建议,并在标准 python (sdot) 中尝试了一个点积。以下是 Python 和 pypy 的 numpy dot (ndot) 计时。
pypy sdot (0.299) 比 python sdot (0.749) 快,并且比两个 ndots (1.075/4.165) 都快,这很好。然而,令我惊讶的是,使用 python 解释器,sdot(python 列表)比 ndot(numpy 数组)更快。
这是为什么?我曾认为 numpy 应该是针对此类事情的优化的快速软件包。
代码如下:
numpy 点积
def runndot(runs):
weightslist = [0.5,0.5,0.5]
weights = np.array(weightslist)
inputslist = [0.1,0.1,0.1]
inputs = np.array(inputslist)
for _ in range(runs):
value = np.dot(inputs,weights)
return value
python 列出点积
def runsdot(runs):
weights = [0.5,0.5]
inputs = [0.1,0.1]
for _ in range(runs):
value = dot(inputs,weights)
return value
def dot(inputs,weights):
sum = 0
for i in range(len(inputs)):
sum += inputs[i]*weights[i]
return sum
解决方法
您正在使用 NumPy,它是用 C 编写的。为了让 PyPy 使用像 NumPy 这样的 c 扩展,它需要跳过一些使 python-c-python 转换变慢的箍。我不知道在 PyPy 上使用 np.dot 的快速替代品,抱歉。有 work afoot 可以实现,但在一两年内无法使用。
您可能对使用 Numba 来加速此类代码感兴趣。
如果你的数组的形状很小,你可以在 python 中手写点积,避免使用 NumPy,并且速度很快。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。