This article mainly introduces the use of the timer Timeit in Python, has a certain reference value, now share to everyone, the need for friends can refer to
This article describes how to use the timer Timeit in Python, and share it with you, as follows:
Timeit
Time.time () is usually used before and after a program, and then subtracted to get the run time of a program, but Python provides a more powerful timing library: Timeit
#导入timeit. Timeitfrom Timeit Import Timeit #看执行1000000次x =1 time: Timeit (' x=1 ') #看x =1 execution time, executed 1 times (number can be omitted, default value is 1000000) : Timeit (' x=1 ', number=1) #看一个列表生成器的执行时间, executed 1 times: Timeit (' [I-I in range (10000)] ', number=1) #看一个列表生成器的执行时间, Performed 10,000 times: Timeit (' [I-I in range] if i%2==0] ', number=10000)
To test the execution time of a function:
From Timeit import timeitdef func (): s = 0 for i in range: s + = i print (s) # Timeit (function name _ string, run Environment _ string, Number= run times) t = Timeit (' func () ', ' from __main__ import func ', number=1000) print (t)
This program tests the execution time of the function 1000 times
Repeat
Because the computer always has other programs are also occupying resources, your program is not the most efficient execution. As a result, many tests are performed, with the minimum execution time being the actual execution time.
From Timeit import repeatdef func (): s = 0 for i in range: s + = I#repeat and Timeit usage are similar, with one repeat parameter, which means repeat test The number of times (can not be written, the default value is 3.), and the return value is a list of times. t = Repeat (' func () ', ' from __main__ import func ', number=100, repeat=5) print (t) print (min (t))