Python内置性能分析----timeit模块
程序员文章站
2024-02-27 12:32:09
...
timeit模块
timeit模块可以用来测试一小段Python代码的执行速度。
class timeit.Timer(stmt='pass', setup='pass', timer=<timer function>)
-
Timer是测量小段代码执行速度的类。
-
stmt参数是要测试的代码语句(statment);
-
setup参数是运行代码时需要的设置;
-
timer参数是一个定时器函数,与平台有关。
timeit.Timer.timeit(number=1000000)
Timer类中测试语句执行速度的对象方法。number参数是测试代码时的测试次数,默认为1000000次。方法返回执行代码的耗时,一个float类型的秒数。
list的操作测试
def t1():
l = []
for i in range(1000):
l = l + [i]
def t2():
l = []
for i in range(1000):
l.append(i)
def t3():
l = [i for i in range(1000)]
def t4():
l = list(range(1000))
from timeit import Timer
timer1 = Timer("t1()", "from __main__ import t1")
print("concat ",timer1.timeit(number=1000), "seconds")
timer2 = Timer("t2()", "from __main__ import t2")
print("append ",timer2.timeit(number=1000), "seconds")
timer3 = Timer("t3()", "from __main__ import t3")
print("comprehension ",timer3.timeit(number=1000), "seconds")
timer4 = Timer("t4()", "from __main__ import t4")
print("list range ",timer4.timeit(number=1000), "seconds")
# ('concat ', 1.7890608310699463, 'seconds')
# ('append ', 0.13796091079711914, 'seconds')
# ('comprehension ', 0.05671119689941406, 'seconds')
# ('list range ', 0.014147043228149414, 'seconds')
insert与append比较
def t2():
li = []
for i in range(10000):
li.append(i)
def t5():
li = []
for i in range(10000):
li.insert(0, i)
timer2 = Timer('t2()', 'from __main__ import t2')
print("append:", timer2.timeit(number=1000))
timer5 = Timer('t5()', 'from __main__ import t5')
print("insert:", timer5.timeit(number=1000))
# append: 0.9202240769991477
# insert: 21.039387496999552
从结果可以看出,append从尾端添加元素效率远远高于insert从顶端添加元素