Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the time execution for each iteration? Python [duplicate]

Tags:

python

I have this code:

for times in range(50):
    factor = (min(getHeight(),getWidth()) / math.sqrt(qtdPosicoes)) * guess()
    positionInGrid = {}
    grid = np.zeros((getGridColumns(),getGridLines()))
    groupMatrix = np.zeros((grid.shape[0], grid.shape[1]))
    groups = getGroups(grid, listaComPosicoes, getXRanges(listaComPosicoes),getYRanges(listaComPosicoes))
    solution = calculaSilhueta()
    if bestSolution is None or solution > bestSolution:
       bestSolution = solution

I found in the documentation time module but I did not understand how to use

like image 683
user2997534 Avatar asked Nov 30 '13 14:11

user2997534


1 Answers

An easy way using this module is to get time.time() to mark the start of your code, and use time.time() again to mark the end of it. After that, substract the them so you can get the duration.

So your code should be like:

for times in range(50):
    start = time.time()
    #do some stuff
    stop = time.time()
    duration = stop-start
    print(duration)

Example:

>>> for i in range(3):
      start = time.time()
      print(i)
      stop = time.time()
      print(stop-start)


0
0.08444404602050781
1
0.014003992080688477
2
0.009001970291137695

But a better option would be to use the timeit module, which is even easier:

>>> import timeit
>>> def myfunction(time):
      print(time)


>>> result = timeit.timeit("for i in range(2): myfunction(i)", setup="from __main__ import myfunction", number=1)
0
1
>>> result
0.0868431608504352

Hope this helps!

like image 110
aIKid Avatar answered Nov 10 '22 08:11

aIKid