timeit模块用于测试一段代码的执行效率
1.Timer类
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 timeitdef f1(): for i in range(1000): passdef f2(): for i in xrange(1000): passt=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.py2.测试Python不同用法的性能
代码:
#copy与deepcopy测试print 'test copy and deepcopy'import copyx=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 jsonimport astprint '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: breakdef while_true(): i=1000 while True: i-=1 if i<1: breakprint '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.000615931092709deepcopy 0.215742113851test json and evaljson 0.0845840788228ast 0.603505149528test while 1 and while Truewhile 1 0.0920688664622while true 0.107391902198map 1.89678050601list parse 0.741696814336filter 1.42262613537list parse 0.631220298896zip 1.26682006617list parse 0.993506476463
结论
- copy比deepcopy快
- json比ast快
- while 1比while True快
- 列表解析比map,filter,zip快 5 r1=[string[i:i+width] for i in xrange(0,len(string),width)] r2=re.findall(r".{%s}"%width,string) r1比r2快