【问题标题】:Which method is faster and why np.sum(arr) vs arr.sum()?哪种方法更快,为什么 np.sum(arr) vs arr.sum()?
【发布时间】:2020-05-21 23:25:52
【问题描述】:

哪种方法更快?好像他们不是一样的吗?

start = time.time()
arr = np.array([1,2,3,4,5,6,7,8,9,0,12])
total_price =  np.sum(arr[arr < 7])* 2.14

print(total_price)
print('Duration: {} seconds'.format(time.time() - start))
start = time.time()
arr = np.array([1,2,3,4,5,6,7,8,9,0,12])
total_price =  (arr[arr<7]).sum()* 2.14

print(total_price)
print('Duration: {} seconds'.format(time.time() - start))

在一次又一次地运行代码时,它们都会给出不同的结果执行时间。前一种方法有时更快,有时更晚。

【问题讨论】:

  • 可能 numpy 更快,但既然你已经有了代码,运行它很多次,看看哪个更快。动手实验将给出最终答案。
  • 如果您要进行基准测试,请不要在正在计时的代码中包含print。并了解timeit
  • 差异应该可以忽略。如果类型已知,我更喜欢arr.sum()。如果类型不支持sum,我猜np.sum 是更通用的方法。
  • @MarkRansom 或者甚至更好地使用 cProfile(或 %prun):P 如果你真的想了解它的细节

标签: python numpy sum time-complexity space-complexity


【解决方案1】:

np.sum 的代码是

def sum(a, axis=None, dtype=None, out=None, keepdims=np._NoValue,
        initial=np._NoValue, where=np._NoValue):

    if isinstance(a, _gentype):
        # 2018-02-25, 1.15.0
        warnings.warn(
            "Calling np.sum(generator) is deprecated, and in the future will give a different result. "
            "Use np.sum(np.fromiter(generator)) or the python sum builtin instead.",
            DeprecationWarning, stacklevel=3)

        res = _sum_(a)
        if out is not None:
            out[...] = res
            return out
        return res

    return _wrapreduction(a, np.add, 'sum', axis, dtype, out, keepdims=keepdims,
                          initial=initial, where=where)

所以它会检查一些参数,然后将任务传递给add.reducesum 方法是“内置”的,但在编译后的代码中必须做类似的事情。

在这些测试中,计算时间本身足够小,调用方法会产生影响:

In [607]: timeit np.sum(np.arange(1000))                                                 
15.4 µs ± 42.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [608]: timeit np.arange(1000).sum()                                                   
12.2 µs ± 29.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [609]: timeit np.add.reduce(np.arange(1000))                                          
9.19 µs ± 17.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

numpy 有许多这样的函数/方法对。使用最方便的 - 并且在您的代码中看起来最漂亮!

【讨论】:

  • 谢谢!我希望这两种方法背后没有复杂的机制。
  • numpy.org/neps/… 谈到了np.sum 在添加了@array_function_dispatch 层的当前版本中的性能。
猜你喜欢
  • 2021-08-03
  • 1970-01-01
  • 1970-01-01
  • 2011-11-14
  • 2021-11-15
  • 1970-01-01
  • 2020-01-25
  • 2016-03-16
  • 2021-04-24
相关资源
最近更新 更多