Introduction
- timeit is a package that comes with python to test the execution time of the code.
How to use
import timeit
Related methods
-
timeit(stmt='pass', setup='pass', timer=<defaulttimer>, number=1000000)
Return:
Return the time used to execute the stmt code number times, in seconds, float type
stmt:要执行的那段代码
setup:执行代码的准备工作,不计入时间,一般是import之类的
timer:这个在win32下是time.clock(),linux下是time.time(),默认的,不用管
number:要执行stmt多少遍
Timer class
The functions in the Timer class are the same as the two functions described above
class timeit.Timer(stmt='pass', setup='pass',timer=<timer function>)
Timer.timeit(number=1000000)
Timer.repeat(repeat=3,number=1000000)
就相当于
timeit(stmt='pass', setup='pass', timer=<defaulttimer>, number=1000000)
= Timer(stmt='pass', setup='pass', timer=<timerfunction>).timeit(number=1000000)
repeat(stmt='pass', setup='pass', timer=<defaulttimer>, repeat=3, number=1000000)
= Timer(stmt='pass', setup='pass', timer=<timerfunction>).repeat(repeat=3, number=1000000)
Let's look at a simple example
import timeit
import math
import pprint
def myfun():
for i in range(100):
for j in range(2, 10):
math.pow(i, 1/j)
n = 100
t1 = timeit.timeit(stmt=myfun, number=n)
pprint.pprint(t1)
t2 = timeit.repeat(stmt=myfun, number=n, repeat=5)
pprint.pprint(t2)
print()
timeitObj = timeit.Timer(stmt=myfun)
t3 = timeitObj.timeit(number=n)
pprint.pprint(t3)
t4 = timeitObj.repeat(number=n, repeat=5)
pprint.pprint(t4)