In Python, we sometimes need to consider the complexity of the algorithm we design, first in Python provides a built-in module that can be used to test the complexity of our algorithm, and then see the use of this module Timeit, first we import the module from Timeit Import Timer, next we need to encapsulate the calculated module of our SU needs into a function, and then use the fixed format
Timer=timer ("def","from__main__ import def")
Where DEF allows us to encapsulate the function, the specific code is as follows
fromTimeitImportTimerdeftest1 (): Li=[] forIinchRange (1000): Li.append (i)deftest2 (): Li=[] forIinchRange (1000): Li+=Ideftest3 (): forIinchRange (1000): Li=[i forIinchRange (1000)]deftest4 (): Li=list (Range (1000)) Timer1=timer ("test1","From __main__ import test1")Print("+:", Timer1.timeit (1000)) Timer2=timer ("test2","From __main__ import test2")Print("+:", Timer2.timeit (1000)) Timer3=timer ("test3","From __main__ import test3")Print("+:", Timer3.timeit (1000)) Timer4=timer ("test4","From __main__ import test4")Print("+:", Timer4.timeit (1000))
Python Timeit module