Implementation of Timeit function, Get performance numbers for a function

July 30, 2019

This is regarding the timeit implementation in python. The basic requirement comes when you want to see how much time your methods are taking. And, on the basis on those numbers you would want to take some action in optimising them.

You should use it on almost every method, and you can use any graphical tool to get the statistics per method. And, you can identify the area which needs improvement.

Implementation of timeit

Below is one implementation of timeit functionality, which implements it as a decorator.

"""
Decorator for taking performance numbers
"""
import time

def perf(method):
    """
    A decorator for fetching time taken by methods
    """
    def timed(*args, **kw):
        # get start time
        start_time = time.time()
        
        # calling the method
        result = method(*args, **kw)
        
        # get end time
        end_time = time.time()

        stats = {}
        stats['method'] = f'{method.__module__}::{method.__qualname__}'
        stats['timetaken'] = '%2.2f' % int((end_time-start_time)*1000)

        print(f'Performance numbers, method={stats["method"]}, timetaken={stats["timetaken"]}')
        return result

    return timed

How to use it

@perf
def test1():
    print('Im in method test1')
    time.sleep(2);

test1()

# Output
Performance numbers, method=__main__::test1, timetaken=2001.00

You can change logging with whatever suits you. I have used print(), but you can use logger to log this in your standard log stream.


Similar Posts

Latest Posts