How to Use the timer timeit in python, And the python timer timeit
This article describes how to use the timer timeit in python. The details are as follows:
Timeit
Usually time. time () is used before and after a program, and then subtract to get the running time of a program. However, python provides a more powerful timing Library: timeit
# Import timeit. timeitfrom timeit import timeit # Check the execution time of 1000000 times x = 1: timeit ('X = 1') # Check the execution time of x = 1 and execute 1 time (number can be omitted, the default value is 1000000): timeit ('X = 1', number = 1) # Check the execution time of a list generator and run it once: timeit ('[I for I in range (10000)]', number = 1) # Check the execution time of a list generator and run it for 10000 times: timeit ('[I for I in range (100) if I % 2 = 0]', number = 10000)
Execution time of a function:
From timeit import timeitdef func (): s = 0 for I in range (1000): s + = I print (s) # timeit (function name_string, runtime environment _ string, number = running times) t = timeit ('func () ', 'From _ main _ import func', number = 1000) print (t)
The execution time of the program to test the function for 1000 times
Repeat:
Because the computer will always have other programs that occupy resources, your program cannot be executed most efficiently. Therefore, multiple tests are generally performed, and the minimum execution time is the actual execution time.
From timeit import repeatdef func (): s = 0 for I in range (1000): s + = I # repeat is similar to timeit usage, with a repeat parameter added, indicates the number of times of repeated tests (this parameter can be left empty. The default value is 3 .), the returned value is a time list. T = repeat ('func () ', 'From _ main _ import func', number = 100, repeat = 5) print (t) print (min (t ))
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.