Python built-in sum function vs. for loop performance

前端 未结 4 1547
野性不改
野性不改 2020-12-03 08:34

I noticed that Python\'s built-in sum function is roughly 3x faster than a for loop when summing a list of 1 000 000 integers:

import timeit

de         


        
4条回答
  •  南笙
    南笙 (楼主)
    2020-12-03 08:59

    As dwanderson suggested, Numpy is one alternative. It is, indeed, if you want to do some maths. See this benchmark:

    import numpy as np
    
    r = range(1000000)       # 12.5 ms
    s = sum(r)               # 7.9 ms
    
    ar = np.arange(1000000)  # 0.5 ms
    as = np.sum(ar)          # 0.6 ms
    

    So both creating the list and summing it is much faster with numpy. This is mostly because the numpy.array is designed for this and is much more efficient than the list.

    However, if we have a python list, then numpy is very slow, as its conversion from a list into a numpy.array is sluggish:

    r = range(1000000)
    ar = np.array(r)         # 102 ms
    

提交回复
热议问题