我在一些模拟中使用 numpy v1.18.2
,并使用内置函数,例如 np.unique
、np.diff
和np.interp
。我在标准对象(即列表或 numpy 数组)上使用这些函数。
当我检查 cProfile
时,我看到这些函数调用了一个内置方法 numpy.core._multiarray_umath.implement_array_function
并且这个方法说明了32.5%
我的运行时间!据我了解,这是一个包装器,它执行一些检查以确保传递给函数的参数与函数兼容。
我有两个问题:
- 这个函数 (
implement_array_function
) 真的占用了这么多时间还是它实际上是我正在做的操作 (np.unique
,np.diff
,np.interp
) 实际上占用了所有时间?也就是说,我是否误解了 cProfile 输出?我对 snakeviz 的分层输出感到困惑。请看snakeviz output here和函数的详细信息 here . - 有没有办法禁用它/绕过它,因为不需要每次都检查输入,因为我传递给这些 numpy 函数的参数已经在我的代码中控制了?我希望这会提高我的表现。
我已经看到这个问题 ( what is numpy.core._multiarray_umath.implement_array_function and why it costs lots of time? ),但我无法理解这个函数到底是什么或做什么。我也试着去理解NEP 18 ,但无法弄清楚如何准确解决问题。请填补我的知识空白并纠正任何误解。 另外,如果有人能像我 5 岁时那样向我解释这一点,我将不胜感激 (r/explainlikeimfive/),而不是假设开发人员级别的 python 知识。
最佳答案
以下所有信息均来自NEP 18 .
Is this function (
implement_array_function
) actually taking up so much time or is it actually the operations I'm doing (np.unique
,np.diff
,np.interp
) that is actually taking up all this time?
正如@hpaulj 在评论中正确提到的那样,调度程序的开销为每个 numpy 函数调用增加了 2-3 微秒。一旦在 C 中实现,这可能会缩短到 0.5-1 微秒。参见 here .
Is there any way to disable it/bypass it
是的,从 NumPy 1.17 开始,您可以将环境变量 NUMPY_EXPERIMENTAL_ARRAY_FUNCTION
设置为 0(在导入 numpy 之前),这将禁止使用 implement_array_function
(参见 here)。有点像
import os
os.environ['NUMPY_EXPERIMENTAL_ARRAY_FUNCTION'] = '0'
import numpy as np
但是,禁用它可能不会给你带来任何显着的性能改进,因为它的开销只有几微秒,这也将是以后的 numpy 版本中的默认设置。
关于python - `built-in method numpy.core._multiarray_umath.implement_array_function` 是性能瓶颈吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61983372/