哪种方法更快,为什么np.sum(arr)vs arr.sum()?

问题描述 投票:0回答:1

哪种方法更快?就像他们俩不一样吗?

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))

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

python numpy sum time-complexity space-complexity
1个回答
2
投票

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具有许多这样的功能/方法对。使用最方便的方式-在您的代码中看起来最漂亮!

© www.soinside.com 2019 - 2024. All rights reserved.