您的位置:首页 > 编程语言 > Python开发

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
'''
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息