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

前端 未结 6 983
时光说笑
时光说笑 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:35

    I got curious and timed it. numpy.sum seems much faster for numpy arrays, but much slower on lists.

    import numpy as np
    import timeit
    
    x = range(1000)
    # or 
    #x = np.random.standard_normal(1000)
    
    def pure_sum():
        return sum(x)
    
    def numpy_sum():
        return np.sum(x)
    
    n = 10000
    
    t1 = timeit.timeit(pure_sum, number = n)
    print 'Pure Python Sum:', t1
    t2 = timeit.timeit(numpy_sum, number = n)
    print 'Numpy Sum:', t2
    

    Result when x = range(1000):

    Pure Python Sum: 0.445913167735
    Numpy Sum: 8.54926219673
    

    Result when x = np.random.standard_normal(1000):

    Pure Python Sum: 12.1442425643
    Numpy Sum: 0.303303771848
    

    I am using Python 2.7.2 and Numpy 1.6.1

提交回复
热议问题