Python timeit module and pythontimeit Module
To test the running time of a piece of code, there is a very simple method in python, that is, using the timeit module, which is super convenient to use.
The following describes a function in the timeit module.
These two functions are used:
1, timeit (stmt = 'pass', setup = 'pass', timer = <defaulttimer>, number = 1000000)
Return Value:
Return the time used to execute the stmt code number times, in seconds, float type
Parameters:
Stmt: code to be executed
Setup: The preparation for executing the code, which is not counted into the time. It is generally an import task.
Timer: this parameter is time. clock () in win32 and time. time () in linux. The default value is not required.
Number: number of times stmt is executed
2, repeat (stmt = 'pass', setup = 'pass', timer = <defaulttimer>, repeat = 3, number = 1000000)
This function has a repeat parameter more than the timeit function, indicating the number of times the timeit process is repeated. A list is returned, indicating the time of each repeat operation.
Of course, for convenience, python also usesTimerThe 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)
You can understand it. In the same way, which O (cost _ convenience) O can be used conveniently?
It is equivalent
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 take a simple example.
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)
Output result:
0.05253329430442725[0.04811309220489818, 0.04411143942591811, 0.04442468209438866, 0.04363309734529072, 0.0596289993101522]0.05972538166968161[0.052578808196427296, 0.047218431876859035, 0.0431364604649378, 0.040855411289408616, 0.04188750572270261]0.04400300979614258
Pprint is an interesting module for better output.