首页 > 解决方案 > 为什么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 的蛇形视图

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

标签: performanceprofilingpypy

解决方案


您正在使用 NumPy,它是用 C 编写的。为了让 PyPy 使用像 NumPy 这样的 c 扩展,它需要跳过一些使 python-c-python 转换缓慢的箍。我不知道在 PyPy 上使用 np.dot 的快速替换,抱歉。实现它的工作正在进行中,但在一两年内不会可用。

您可能对使用 Numba 来加速此类代码感兴趣。

如果你的数组的形状很小,你可以在 python 中手写点积,避免 NumPy,并且速度很快。


推荐阅读