Python比较for循环、列表解析、迭代器、map之间运算时间关系
2016-01-02 21:19
871 查看
# -*- coding:utf-8 -*-、 ''' Dedign a timer to compare the runtime the following function: for...loop listComprehension generator map ''' #Initialize bound of the size. size = 1000000 #import time module to calculate time import time,sys #Design a Timer def runTimeTester(func,*args): startTime = time.time() for eachFunc in range(size): func(*args) runTime = time.time() - startTime #calculate runtime return runTime #for loop def forLoop(): res = [] for x in range(size): res.append(x**2) #list comprehension def listComprehension(): res = [x**2 for x in range(size)] #generator expression def generatorExpression(): res = (x**2 for x in range(size)) #map function def mapFunction(): res = map(lambda x:x**2,range(size)) #main function print sys.version sys.stdout.write("Calculate runtime of each function.\n") print "-"*40 print "functionName","\t\t\t","runTime" print "-"*20,"\t","-"*16 #测试 if __name__ == '__main__': func = [forLoop,listComprehension,generatorExpression,mapFunction] for eachFunc in func: print eachFunc.__name__.ljust(20),">>",runTimeTester(eachFunc) #运行结果 ''' forLoop >> 1.5 listComprehension >> 1.41999983788 generatorExpression >> 0.0239999294281 mapFunction >> 1.4430000782 '''
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- 设计模式之行为型模式 - 调用行为的传递问题
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例