Python's sum vs. NumPy's numpy.sum

前端 未结 6 968
时光说笑
时光说笑 2020-11-28 08:03

What are the differences in performance and behavior between using Python\'s native sum function and NumPy\'s numpy.sum? sum works on

6条回答
  •  借酒劲吻你
    2020-11-28 08:25

    This is an extension to the the answer post above by Akavall. From that answer you can see that np.sum performs faster for np.array objects, whereas sum performs faster for list objects. To expand upon that:

    On running np.sum for an np.array object Vs. sum for a list object, it seems that they perform neck to neck.

    # I'm running IPython
    
    In [1]: x = range(1000) # list object
    
    In [2]: y = np.array(x) # np.array object
    
    In [3]: %timeit sum(x)
    100000 loops, best of 3: 14.1 µs per loop
    
    In [4]: %timeit np.sum(y)
    100000 loops, best of 3: 14.3 µs per loop
    

    Above, sum is a tiny bit faster than np.array, although, at times I've seen np.sum timings to be 14.1 µs, too. But mostly, it's 14.3 µs.

提交回复
热议问题