热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

numpy的快体现在哪儿

1、本文主要对传统for循环,sum函数,以及numpy包中的sum函数的执行快慢进行比较for循环:sum_by_for="""for d in d

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)

 


推荐阅读
author-avatar
男孩形式恋人
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有