How to Find the total elapsed time for any function or any routine in python

403 Views Asked by At

currently i'm using the below code to find elapsed time for any routine/functions that i manually use start time and end time all that

But, i want a fuction should automatically return the entire function took how long as if like when we run query and it use to say how many seconds and milli seconds like that i want to run any function and each function should return me with that elapsed time.

and here is my code and absolutely i'm not happy with this and i want a high end professional line of code's pls help. Thanks.

def ElaspedTime(stime,etime):
    from datetime import timedelta
    timediff = timedelta(seconds=etime - stime)
    return timediff

def STime():
    return time.monotonic()

def ETime():
    return time.monotonic()

#start_time = time.monotonic()

##call functions here

#end_time = time.monotonic()

#print( ElaspedTime(start_time,end_time))
2

There are 2 best solutions below

1
RaphaMex On

You can create a wrapper function like this:

def runWithTime(f,*args):
    from datetime import timedelta
    import time
    stime = time.time()
    r = f(*args)
    etime = time.time()
    timediff = timedelta(etime - stime)
    print timediff
    return r

def a(x,y):
    return x+y

r = runWithTime(a,1,2)
print r
0
farax On

write a decorator as follow (replace log.debug with print ...):

from functools import wraps
def with_stopwatch(f):
    @wraps(f)
    def wrapped(*args, **kw):
        tstart = time()
        result = f(*args, **kw)
        tend = time()
        log.debug('>>> func:%r took: %2.4f sec' % (f.__name__, tend - tstart))
        return result
    return wrapped

@with_stopwatch
def function()
    ...