performance - 为什么pypy3比python慢
问题描述
为了更快地运行我的代码,我认为 pypy 只是工作。但是,我发现我的某些代码实际上更慢。
有人可以帮我理解为什么会这样吗?
这是我在functions.py的第663行识别出的调用(加权和),它在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, 0.5, 0.5]
weights = np.array(weightslist)
inputslist = [0.1, 0.1, 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, 0.5, 0.5, 0.5]
inputs = [0.1, 0.1, 0.1, 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 的快速替换,抱歉。实现它的工作正在进行中,但在一两年内不会可用。
您可能对使用 Numba 来加速此类代码感兴趣。
如果你的数组的形状很小,你可以在 python 中手写点积,避免 NumPy,并且速度很快。
推荐阅读
- android - 即使我使用正确的 IP 地址,也无法在 android 中托管异常?
- mysql - 将 MySql 查询与 Sphinx 查询相结合?
- c++ - 为什么我得到类不是模板错误?
- angular -
内部不工作 离子 4 - laravel - 如何在谷歌图表库的刻度区域网格中显示颜色
- mongodb - MongoDB中$和$$的区别
- delphi - Delphi,将PNG图像的内容复制到另一个不同大小的PNG图像
- python - 删除数组中的最后一个值(使用 Numpy)
- database - 如何解决 Go 编程语言中的数据库结构问题?
- kubernetes - 关于如何将 docker push 推送到在 kubernetes 中运行的 docker-registry 的示例