I have some problems in timing in python

Viewed 74

I'm trying to learn python from the book https://www.amazon.com/Learning-Python-5th-Mark-Lutz/dp/1449355730 and I have some problems in chapter 21 that is about timing in python

this book has given this module to get operation time of functions :

"""
homegrown timing tools for function calls.
Does the total-time, best-of-time, and best of totals time.
"""
import time , sys 
timer = time.perf_counter

def total(reps , func , *pargs , **kargs) :
    replist = list(range(reps))
    start   = timer() 
    for i in replist :
        ret = func(*pargs , **kargs) 
    
    elapsed = timer() - start 
    return (elapsed , ret) 


def bestof (reps , func , *pargs , **kargs) :
    best = 2 ** 32 
    for i in range(reps) :
        start = timer()
        ret = func(*pargs , **kargs) 
        elapsed = timer() - start  
        if elapsed < best : best = elapsed 
    
    return (best , ret)



def bestoftotal(reps1 ,reps2 , func , *pargs , **kargs ) :
    return bestof(reps1 , total , reps2  , func , *pargs , **kargs) 

the first function gives us the total time of a function when we call it 1000 times the second one calculates the time of each 1000 time operation and gives the best one and the third one gives the best of totals, mean that calculates totals and gives the best one (min time ), my problem here is exactly in the third one. in the main program I'm trying to run it and please look at the output :

import timer 
A= timer.bestoftotal(1000 , 1000 , pow , 2 , 1000)
print('pow best totals : ' ,A[0]  , A[1][0])

and this is my output

PS C:\Users\Ata Barzegar\Desktop\learn> & "C:/Users/Ata Barzegar/AppData/Local/Programs/Python/Python37/python.exe" "c:/Users/Ata Barzegar/Desktop/learn/learnpy.py"
pow best totals :  0.0011224999999999152       0.001119799999999893

the problem is that we are trying to get the minimum time of total but the second number is smaller than the first one,plz help me Also, I should mention this does not happen every time.

1 Answers
def bestof(reps, func, *pargs, **kargs):
    best = 2 ** 32
    best_ret = None
    for i in range(reps):
        start = timer()
        ret = func(*pargs, **kargs)
        elapsed = timer() - start
        if elapsed < best:
            best = elapsed
            best_ret = ret
    return (best, best_ret)

in bestof function, you always return the last ret. So, if you want to compare those two timings, you should declare a best_ret and return it

Related