27.5. timeit — Measure execution time of small code snippets
Source code: Lib/timeit.py
timeit模块可以用来测试一段代码的执行耗时,如一个变量赋值语句的执行时间,一个函数的运行时间。
timeit是标准模块,无需安装。
import timeit
模块定义了三个方法和一个公共类。
Create a Timer instance with the given statement, setup code and timer function and run its timeit() method with number executions. The optional globals argument specifies a namespace in which to execute the code.
参数说明:
Create a Timer instance with the given statement, setup code and timer function and run its repeat() method with the given repeat count and number executions. The optional globals argument specifies a namespace in which to execute the code.
参数说明:
The default timer, which is always time.perf_counter().
Changed in version 3.3: time.perf_counter() is now the default timer.
Class for timing execution speed of small code snippets.
注意事项:
import timeit def _test_timeit(): global a # timeit a = [1,2,3,4] t = timeit.timeit(stmt=‘_test_2(a)‘, setup=‘from __main__ import _test_2, a‘, number=100000) print(t) # repeat a = [1,2,3,4] t = timeit.repeat(stmt=‘_test_2(a)‘, setup=‘from __main__ import _test_2, a‘, number=1000000, repeat=5 ) print(t) def _test_2(s=None, *ar): #s.insert(0, 45) s.append(55) if __name__ == ‘__main__‘: a = None _test_timeit() pass
输出:
0.02622983706364665 [0.28630844773090425, 0.2964419925588122, 0.23573263042489412, 0.2578145301438086, 0.22425034115163478]
说明:
repeat()与timeit()的区别在于它会重复测试多次,返回单次执行时间所组成的列表。
timer()实质是timeit()和repeat()的底层实现;
def timeit(stmt="pass", setup="pass", timer=default_timer, number=default_number, globals=None): """Convenience function to create Timer object and call timeit method.""" return Timer(stmt, setup, timer, globals).timeit(number) def repeat(stmt="pass", setup="pass", timer=default_timer, repeat=default_repeat, number=default_number, globals=None): """Convenience function to create Timer object and call repeat method.""" return Timer(stmt, setup, timer, globals).repeat(repeat, number)
也可以使用Timer()初始化然后调用其方法timeit和repeat。
原文:https://www.cnblogs.com/wodeboke-y/p/12374237.html