首页 > 代码库 > Python timeit

Python timeit

 

timeit模块:

1) timeit.timeit(stmt=‘pass‘, setup=‘pass‘, timer=<defaulttimer>, number=1000000)

返回:返回执行stmt这段代码number遍所用的时间,单位为秒,float型
参数:stmt:要执行的那段代码
setup:执行代码的准备工作,初始化代码或构建环境导入语句,不计入时间,一般是import之类的
timer:这个在win32下是time.clock(),linux下是time.time(),默认的,不用管
number:要执行stmt多少遍

 

import timeitprint timeit.timeit("sum(x)","x=(i for i in range(100))")0.114394682716def test():    L = [i for i in range(100)]#在setup中导入自定义函数if __name__ == __main__:    import timeit    print(timeit.timeit("test()", setup="from __main__ import test",number=10000))0.0800761957937

 

 

2) repeat(stmt=‘pass‘, setup=‘pass‘, timer=<defaulttimer>, repeat=3, number=1000000)

这个函数比timeit函数多了一个repeat参数而已,表示重复执行timeit这个过程多少遍,返回一个列表,表示执行每遍的时间
当然,为了方便,python还用了一个Timer类,Timer类里面的函数跟上面介绍的两个函数是一样一样的

import timeitt = timeit.Timer(char in text, setup=text = "I love FishC.com!"; char = "o")t.timeit()0.054789127320191255t.repeat()[0.05562128719998327, 0.046032358580077926, 0.044957160393096274]

 

3) timeit.default_timer()

默认的计时器

 

import timeits1=timeit.default_timer()n=0for i in range(101):        n+=id1=timeit.default_timer()        d1-s10.00017283636378806477

 

4)

Timer类,Timer类里面的函数跟上面介绍的两个函数是一样一样的

class timeit.Timer(stmt=‘pass‘, setup=‘pass‘,timer=<timer function>)

Timer.timeit(number=1000000)

Timer.repeat(repeat=3,number=1000000)

def test():    L = [i for i in range(100)]    timeObj=timeit.Timer(stmt="test()",setup="from __main__ import test")print timeObj.timeit(number=2)3.16114014822e-05print timeObj.repeat(repeat=5)[5.158685950990275, 4.8465939741281545, 4.779073662776227, 4.764550071228314, 4.747949980088833]
import timeitimport mathimport pprintdef myfun():    for i in range(100):        for j in range(2, 10):            math.pow(i, 1/j)n = 100t1 = 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)0.029213861394509877[0.03452991382800974, 0.03289597385673915, 0.031878661483006, 0.03200839139026357, 0.03210733097148477]()0.021823362057602935[0.024504583653197187, 0.02141200330106585, 0.02137833921096899, 0.021332358990548528, 0.022017956918261916]

 

5)命令行调用

python -m timeit [-n N] [-r N] [-s S] [-t] [-c] [-h] [statement...]

-n N 执行指定语句的次数
-r N 重复测量的次数(默认3次)
-s S 指定初始化代码活构建环境的导入语句(默认pass)
python 3.3新增
-t 使用time.time() (不推荐)
-c 使用time.clock() (不推荐)
-v 打印原始计时结果
-h 帮助

$ python -m timeit "-".join(str(n) for n in range(100))10000 loops, best of 3: 40.3 usec per loop$ python -m timeit "-".join([str(n) for n in range(100)])10000 loops, best of 3: 33.4 usec per loop$ python -m timeit "-".join(map(str, range(100)))10000 loops, best of 3: 25.2 usec per loop

 

Python timeit