# pythonwhile、for、生成器、列表推导等语句的执行效率测试

import time,sys
reps = 1000 #测试重复次数
nums = 200000 #测试时数字大小

def tester(func,*args): #总体测试函数
starttime = time.time()
for i in range(reps):
func(*args)
elapsed = time.time() – starttime #用time模块来测试，结束时间与开始时间差
return elapsed

def while_statement(): #while循环实现
res = []
x = 0
while nums > x:
x += 1
res.append(abs(x))

def for_statement(): #for循环实现
res = []
for x in range(nums):
res.append(abs(x))

def generator_expression():#生成器实现
res = list(abs(x) for x in range(nums))

def list_comprehension(): #列表解析实现
res = [abs(x) for x in range(nums)]

def map_function(): #内置函数map实现
res = map(abs, range(nums))

print sys.version #打印系统版本
tests = [while_statement, for_statement, generator_expression, list_comprehension, map_function]
for testfunc in tests: #将待测函数放置列表中依次遍历
print testfunc.__name__.ljust(20),’: ‘,tester(testfunc) #

>>>
2.7.4 (default, apr 6 2013, 19:55:15) [msc v.1500 64 bit (amd64)]
while_statement : 84.5769999027
for_statement : 75.2709999084
generator_expression : 62.3519999981
list_comprehension : 60.4090001583
map_function : 47.5629999638

import sys
nums = 100

def while_statement():
res = []
x = 0
while nums > x:
x += 1
res.append(abs(x))

def for_statement():
res = []
for x in range(nums):
res.append(abs(x))

def generator_expression():
res = list(abs(x) for x in range(nums))

def list_comprehension():
res = [abs(x) for x in range(nums)]

def map_function():
res = map(abs, range(nums))

if __name__==’__main__’:
import timeit #用timeit模块来测试
print sys.version
funcs = [while_statement, for_statement, generator_expression, list_comprehension, map_function]
for func in funcs:
print func.__name__.ljust(20),’: ‘,timeit.timeit(“func()”, setup=”from __main__ import func”)

>>>
2.7.4 (default, apr 6 2013, 19:55:15) [msc v.1500 64 bit (amd64)]
while_statement : 37.1800067428
for_statement : 30.3999109329
generator_expression : 27.2597866441
list_comprehension : 17.386223449
map_function : 12.7386868963

Posted in 未分类