测试某一行代码或者某个函数的运行时间,在python中通过timeit模块测试:
(1)如果测试某一个函数:
import timeit
def test1(): l=[] for i in range(1000): l=l+[i]
def test2(): l=[] for i in range(1000): l.append(i) def test3(): l=[i for i in range(1000)]
def test4(): l=list(range(1000))
t1=timeit.Timer("test1()","from __main__ import test1") print("connact",t1.timeit(number=1000),"millisecond")
t2=timeit.Timer("test2()","from __main__ import test2") print("append",t2.timeit(number=1000),"millisecond")
测试结果:
connact 2.1764626640482447 millisecond append 0.12423578134195168 millisecond
(2)如果测试某一行代码运行的时间:
import timeit
t2=timeit.Timer('x=range(1000)')
print(t2.timeit())
运行结果:0.5157291338798018 millisecond