timeit library ：
timeit The library defines... That takes two parameters Timer class . Both parameters are strings . The first parameter is the statement or function to be timed ; The second parameter is the import statement that builds the environment for the first parameter statement . Tell from the internal , timeit Build an independent virtual environment , Execute the build statement manually , Then compile and execute the timed statement manually .
Once there is Timer object , The easiest thing to do is call timeit(), It accepts a parameter that calls the number of timed statements for each test. , Default is one million times ; Number of seconds taken to return .
Test a list derivation and for Cycle time ：
import timeit foooo = """ sum =  for i in range(1000): sum.append(i) """ print(timeit.timeit(stmt="[i for i in range(1000)]", number=100000)) print(timeit.timeit(stmt=foooo, number=100000)) # result # 3.0098994999999604 # 5.630418200000008
adopt 10w Secondary cycle , It is found that the use of list derivations is better than the normal use of list Adding elements will bring you closer and closer 5 About seconds , Nearly three times faster .
timeit The library abstracts two methods that can be used directly , Let's take a look at the code in the module ：
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)
Test the execution time of a function ：
from timeit import timeit def func(): s = 0 for i in range(1000): s += i print(s) # timeit( Function name _ character string , Running environment _ character string ,number= Number of runs ) t = timeit('func()', 'from __main__ import func', number=1000) print(t)
Because computers always have other programs that take up resources , Programs cannot be executed most efficiently . So it's usually done many times , Take the minimum execution time as the real execution time .
from timeit import repeat def func(): s = 0 for i in range(1000): s += i #repeat and timeit Similar usage , One more. repeat Parameters , The number of times the test was repeated ( Don't write , The default value is 3.), The return value is a list of times . t = repeat('func()', 'from __main__ import func', number=100, repeat=5) print(t) print(min(t))