[Base] Python Python powerful timing library timeit

Python powerful timing library timeit

Before and after a program usually have to spend time.time (), then subtract run time you can get a program, but provides a more powerful python timing library: timeit

Test line statement execution time

# Import timeit.timeit 
from the timeit Import the timeit   

# see performed 1,000,000 times x = 1: 
the timeit ( ' x = 1 ' ) 

# see x = 1 execution time is performed once (number default value 1,000,000): 
the timeit ( ' X = 1 ' , Number = 1 ) 

# see a list of the execution time generator, performed once: 
the timeit ( ' [I for I in Range (10000)] ' , Number = 1 ) 

# see a list generator execution time, execution 10,000: 
the timeit ( ' [I for I in Range (100)% 2 == 0 IF I] ' , Number = 10000)

Perform a function test of time

from the timeit Import the timeit 

DEF FUNC (): 
    S = 0
     for I in Range (1000 ): 
        S + = I
     Print (S) 

# the timeit (String function name _, _ operating environment string, number = number of runs) 
T = the timeit ( ' FUNC () ' , ' from __main__ Import FUNC ' , Number = 1000 )
 Print (T)

This function runs a test program execution time 1000

  • repeat:

Since the computer always have other programs that also take up the resources, you can not be the most efficient program execution. So usually we carried out several tests, taking a minimum execution time for real time execution.

from timeit Import repeat 

DEF FUNC (): 
    S = 0
     for I in Range (1000 ): 
        S + = I 

# repeat usage and timeit similar repeat one more parameter indicates the number of repeated tests (can not write, the default value 3), the return value is a list of time. 
REPEAT = T ( ' FUNC () ' , ' from __main__ Import FUNC ' , Number = 100, REPEAT =. 5 )
 Print (T) 
 Print (min (T))

 

Reference: https://cloud.tencent.com/developer/article/1406467

 

Guess you like

Origin www.cnblogs.com/XJT2018/p/11039415.html
Recommended