Timing functions in Python

Recently I saw a blogpost on tracking time in Python. This is inspired me to share how I track time in my python scripts. First I put the following python decorator function in my code or preferably import it from a common module.

import time                                                

def timeit(method):

    def timed(*args, **kw):
        ts = time.time()
        result = method(*args, **kw)
        te = time.time()

        print('%r (%r, %r) %2.2f sec' % (method.__name__, args, kw, te-ts))
        return result

    return timed

You can use the timeit function like this:

@timeit
def longRunningOperation(dummyArg, optionalDummyArg=None):
    time.sleep(3)
    
longRunningOperation("test", "optional test")

The output of the timeit decorator function looks like this:

'longRunningOperation' (('test', 'optional test'), {}) 3.00 sec

As you can see, the timit function reports the function name, the passed arguments and the elapsed time

If you want to learn more about decorator functions I would suggest to read the python.org wiki article on decorators. On the same site there is also an article with useful decorator functions for things like caching, properties, pre- and post conditions, memoization and many more.

1 comment:

Pontus Fransson said...

You provide such a great post over here i am going to share this post in my circle actually one of my friend is also looking for this post. Keep sharing