Test the execution speed of append and insert in the list

  • The timeit module can be used to test the execution speed of a small piece of Python code.
  • 1 class timeit.Timer(stmt='pass', setup='pass', timer=<timer function>)
  • Timer is a class that measures the execution speed of small pieces of code. The stmt parameter is the code statement to be tested (statment); the setup parameter is the setting required to run the code; the timer parameter is a timer function, which is related to the platform.
  • 1 timeit.Timer.timeit(number=1000000)
  • The object method of the Test statement execution speed in the Timer class. The number parameter is the number of tests when testing code, and the default is 1000000 times. The method returns the average time spent executing the code, a number of seconds of type float.
  •  1 from timeit import Timer
     2 #定义append_test
     3 def append_test():
     4     li = []
     5     for i in range(10000):
     6         li.append(i)
     7 def insert_test():
     8     li = []
     9     for i in range(10000):
    10         li.insert(0,i)
    11 #测试执行时间
    12 append_timer = Timer('append_test()',' from __main__ import append_test ' )
     13  print ( ' append insert execution time: ' , append_timer.timeit (1000 ))
     14 insert_timer = Timer ( ' insert_test () ' , ' from __main__ import insert_test ' )
     15  print ( ' insert insert execution Time: ' , insert_timer.timeit (1000))
  • 1 append insert execution time: 1.8698293
     2 insert insert execution time: 43.3934531

     

Guess you like

Origin www.cnblogs.com/monsterhy123/p/12759789.html