1、本文主要对传统for循环,sum函数,以及numpy包中的sum函数的执行快慢进行比较
for循环:
sum_by_for="""
for d in data:s+=d
"""
sum函数:
sum_by_sum="""
sum(data)
"""
numpy中的sum函数:
sum_by_numpy="""
import numpy
numpy.sum(data)
"""
2、本文针对上述三种方法,分别对list,array和numpy数据形式用上述三种方法进行比较:
list:
def timeit_using_list(n,loops):list_setup="""
data=[1]*{}
s=0
""".format(n)print('list result:')print(timeit.timeit(sum_by_for,list_setup,number=loops))print(timeit.timeit(sum_by_sum,list_setup,number=loops))print(timeit.timeit(sum_by_numpy,list_setup,number=loops))
array:
def timeit_using_array(n,loops):array_setup="""
import array
data=array.array('L',[1]*{})
s=0
""".format(n)print('array result:')print(timeit.timeit(sum_by_for,array_setup,number=loops))print(timeit.timeit(sum_by_sum,array_setup,number=loops))print(timeit.timeit(sum_by_numpy,array_setup,number=loops))def
numpy:
def timeit_using_numpy(n,loops):numpy_setup="""
import numpy
data=numpy.array([1]*{})
s=0
""".format(n)print('numpy result:')print(timeit.timeit(sum_by_for,numpy_setup,number=loops))print(timeit.timeit(sum_by_sum,numpy_setup,number=loops))print(timeit.timeit(sum_by_numpy,numpy_setup,number=loops))
3、实验结果对比
全部代码:
import timeitsum_by_for="""
for d in data:s+=d
"""sum_by_sum="""
sum(data)
"""sum_by_numpy="""
import numpy
numpy.sum(data)
"""def timeit_using_list(n,loops):list_setup="""
data=[1]*{}
s=0
""".format(n)print('list result:')print(timeit.timeit(sum_by_for,list_setup,number=loops))print(timeit.timeit(sum_by_sum,list_setup,number=loops))print(timeit.timeit(sum_by_numpy,list_setup,number=loops))def timeit_using_array(n,loops):array_setup="""
import array
data=array.array('L',[1]*{})
s=0
""".format(n)print('array result:')print(timeit.timeit(sum_by_for,array_setup,number=loops))print(timeit.timeit(sum_by_sum,array_setup,number=loops))print(timeit.timeit(sum_by_numpy,array_setup,number=loops))def timeit_using_numpy(n,loops):numpy_setup="""
import numpy
data=numpy.array([1]*{})
s=0
""".format(n)print('numpy result:')print(timeit.timeit(sum_by_for,numpy_setup,number=loops))print(timeit.timeit(sum_by_sum,numpy_setup,number=loops))print(timeit.timeit(sum_by_numpy,numpy_setup,number=loops))if __name__=='__main__':timeit_using_list(30000,500)timeit_using_array(30000,500)timeit_using_numpy(30000,500)