timeit模块用于测试一段代码的执行效率
Timer 类:
__init__(stmt="pass", setup="pass", timer=default_timer)
stmt 是执行语句,setup 是导入执行语句环境
print_exc(file=None)
timeit(number=default_number)
返回测试所用秒数,number 是每个测试中调用被计时语句的次数
repeat(repeat=default_repeat, number=default_number)
返回测试所用秒数列表,repeat 是重复整个测试的次数,number 是每个测试中执行语句的次数
快捷执行的方法:
timeit.timeit('time.time()','import time',number=10)
#这里会执行两次测试,每次测试都执行time.time()语句10次
timeit.repeat('time.time()','import time',repeat=2,number=10)
DEMO
import timeit
def f1():
for i in range(1000):
pass
def f2():
for i in xrange(1000):
pass
t=timeit.Timer('f1()','from __main__ import f1')
t1=timeit.Timer('f2()','from __main__ import f2')
print t.timeit()
print t1.timeit()
查看一个脚本的执行效率
python -m cProfile test_cprofile.py
代码:
#copy与deepcopy测试
print 'test copy and deepcopy'
import copy
x=range(1000)
print 'copy',timeit.timeit('copy.copy(x)','from __main__ import copy,x',number=100)
print 'deepcopy',timeit.timeit('copy.deepcopy(x)','from __main__ import copy,x',number=100)
#json和eval测试
import json
import ast
print 'test json and eval'
d=dict([(i,i) for i in xrange(1000)])
def test_json():
json.loads(json.dumps(d))
def test_ast():
ast.literal_eval(str(d))
print 'json',timeit.timeit('test_json()','from __main__ import test_json',number=100)
print 'ast',timeit.timeit('test_ast()','from __main__ import test_ast',number=100)
#while 1 和while True测试
print 'test while 1 and while True'
def while_one():
i=1000
while 1:
i-=1
if i<1:
break
def while_true():
i=1000
while True:
i-=1
if i<1:
break
print 'while 1',timeit.timeit('while_one()','from __main__ import while_one',number=1000)
print 'while true',timeit.timeit('while_true()','from __main__ import while_true',number=1000)
#测试map和列表解析
print 'map',timeit.timeit('map(lambda x:x+10,xrange(10000))',number=1000)
print 'list parse',timeit.timeit('[x+10 for x in xrange(10000)]',number=1000)
#测试filter和列表解析
print 'filter',timeit.timeit('filter(lambda x:x<5000,xrange(10000))',number=1000)
print 'list parse',timeit.timeit('[x for x in xrange(10000) if x<5000]',number=1000)
#测试zip和列表解析
d=[(i,i+1,i+2) for i in xrange(10000)]
print 'zip',timeit.timeit('zip(*d)[0]','from __main__ import d',number=1000)
print 'list parse',timeit.timeit('[x[0] for x in d]','from __main__ import d',number=1000)
测试结果:
test copy and deepcopy
copy 0.000615931092709
deepcopy 0.215742113851
test json and eval
json 0.0845840788228
ast 0.603505149528
test while 1 and while True
while 1 0.0920688664622
while true 0.107391902198
map 1.89678050601
list parse 0.741696814336
filter 1.42262613537
list parse 0.631220298896
zip 1.26682006617
list parse 0.993506476463
结论
参考博客