The python module timeit

timeit modules:

  • timeit module defines Timer class accepts two parameters. Both arguments are strings. The first argument is that you should timed statement or function. Timer passed to the second parameter is the import statement for the first environment parameter statement. Internally, timeit build a separate virtual environment, manually executes the setup statement, then manually compiles and executes the timed statement.

  • Once you have the Timer object, the easiest thing is to call timeit (), which accepts one parameter is the number of the timed statement of each test call, the default is a million times; returns the number of seconds it takes.

  • Another major method of the Timer object is repeat (), which accepts two optional parameters. The first parameter is the number of repeat the entire test, the second parameter is the number of the timed statement of each test call. Two parameters are optional, their default values ​​are 3 and 1,000,000. repeat () method returns a list of the times per second recorded test cycle. Python has a handy min function can return a list of the minimum value of the input, such as: min (t.repeat (3, 1000000))

  A list of test time derivation of the formula for loop

1
2
3
4
5
6
7
8
9
10
11
12
13
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 ))
 
#res:
#3.2855970134734345
#8.19918414604134

  Using the list comprehension than the normal use of additional list elements will cycle through 10w of nearly 5 seconds faster, nearly three times the speed.

  timeit module abstracted; two methods can be used directly, pack a layer lets us do not care about internal implementation, look at the following code inside the module:

1
2
3
4
5
6
7
8
9
def  timeit(stmt = "pass" , setup = "pass" , timer = default_timer,
            number = default_number):
     """Convenience function to create Timer object and call timeit method."""
     return  Timer(stmt, setup, timer).timeit(number)
 
def  repeat(stmt = "pass" , setup = "pass" , timer = default_timer,
            repeat = default_repeat, number = default_number):
     """Convenience function to create Timer object and call repeat method."""
     return  Timer(stmt, setup, timer).repeat(repeat, number)

  This can be seen two methods are based on the packet layer Timer these parameters:

  stmt: This parameter is the statement, the code can be placed inside the computing time. He could accept the expression string directly, or you can accept a single variable, the function can accept.

  setup: This parameter can be stmt pass in the environment. For example, a variety of import and parameters or something.

  timer: This parameter is generally not used, the specific use can be found in the document.

  There Timer class repeat and timeit use the following method is also very convenient timeit.timeit and timeit.repeat.

  The above is an example of a timeit, a fact that repeat repeat on more parameters than the number of times an executive Timer timeit. The number of executions is returned as an array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import  timeit
 
foooo  =  """
sum = []
for i in range(1000):
     sum.append(i)
"""
 
print (timeit.repeat(stmt = "[i for i in range(1000)]" , repeat = 2 , number = 100000 ))
print ( min (timeit.repeat(stmt = "[i for i in range(1000)]" , repeat = 2 , number = 100000 )))
 
#res:
#[3.4540683642063277, 3.300991128415932]
#3.321008256502136

  According to this we can, takes a minimum value min of all the execution time, average, maximum, we want to obtain data.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# coding: utf-8
import  timeit
 
# 初始化类
=  """
say_hi.ParseFromString(p)
"""
 
=  """
simplejson.loads(x)
"""
 
print (timeit.timeit(stmt = x, setup = "import say_hi_pb2;"
                                   "say_hi = say_hi_pb2.SayHi();"
                                   "say_hi.id = 13423;"
                                   "say_hi.something = 'axiba';"
                                   "say_hi.extra_info = 'xiba';"
                                   "p =say_hi.SerializeToString()" , number = 1000000 ))
 
print (timeit.timeit(stmt = y, setup = "import simplejson; "
                                   "json={"
                                   "'id': 13423,"
                                   "'something': 'axiba',"
                                   "'extra_info': 'xiba',"
                                   "};"
                                   "x = simplejson.dumps(json)" , number = 1000000 ))<br> 

另外需要补充一点是,如果你想直接 stmt 那里执行函数。可以把函数申明在当前文件中,然后在 stmt = ‘func()’ 执行函数。然后使用 setup = ‘from __main__ import func’ 即可,如果要import 多个需要使用 setup = from __main__ import func; import simplejson'

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
def  test1():
     n = 0
     for  in  range ( 101 ):
         n + = i
     return  n
def  test2():
     return  sum ( range ( 101 ))
def  test3():
     return  sum (x  for  in  range ( 101 ))
if  __name__ = = '__main__' :
     from  timeit  import  Timer
     t1 = Timer( "test1()" , "from __main__ import test1" )
     t2 = Timer( "test2()" , "from __main__ import test2" )
     t3 = Timer( "test3()" , "from __main__ import test3" )
     print (t1.timeit( 10000 ))
     print (t2.timeit( 10000 ))
     print (t3.timeit( 10000 ))
     print (t1.repeat( 3 , 10000 ))
     print (t2.repeat( 3 , 10000 ))
     print (t3.repeat( 3 , 10000 ))
     t4  =  timeit.timeit(stmt = test1,setup = "from __main__ import test1" ,number = 10000 )
     t5  =  timeit.timeit(stmt = test2,setup = "from __main__ import test2" ,number = 10000 )
     t6  =  timeit.timeit(stmt = test3,setup = "from __main__ import test3" ,number = 10000 )
     print (t4)  #0.05130029071325269
     print (t5)  #0.015494466822610305
     print (t6)  #0.05650903115721077
     print (timeit.repeat(stmt = test1,setup = "from __main__ import test1" ,number = 10000 ))  # [0.05308853391023148, 0.04544335904366706, 0.05969025402337652]
     print (timeit.repeat(stmt = test2,setup = "from __main__ import test2" ,number = 10000 ))  # [0.012824560678924846, 0.017111019558035345, 0.01429126826003152]
     print (timeit.repeat(stmt = test3,setup = "from __main__ import test3" ,number = 10000 ))  # [0.07385010910706968, 0.06244617606430164, 0.06273494371932059]
 
#res:
0.043916918200588385
0.014892355541932578
0.05214884436618059
[ 0.04372713709398021 0.04197132052492908 0.04255431716177577 ]
[ 0.014356804181737959 0.012456603785177323 0.012629659578433372 ]
[ 0.0543709217115389 0.05334180294099272 0.05334931226535494 ]

  

Guess you like

Origin www.cnblogs.com/valorchang/p/11282126.html