Jun 2, 2019

Python decorator to find out execution time taken by a function

import functools
import time

def timer(f): # without functools.wraps
    def timer_wrap(*args, **kwargs):
        """timer_wrap documentation """
        print('inside timer_wrap decorator')
        start_time = time.time()
        f(*args, **kwargs)
        end_time = time.time()
        print('Total Time Taken by function %s is : %4f secs' % (f.__name__, end_time - start_time))
        # f.__name__ gives function name
    return timer_wrap

def timer_wrap_with_functools(f): # with functools.wraps
    @functools.wraps(f)
    def timer_wrap(*args, **kwargs):
        """timer_wrap_with_functools documentation """
        print('inside timer_wrap_with_functools decorator')
        start_time = time.time()
        f(*args, **kwargs)
        end_time = time.time()
        print('Total Time Taken by function %s is : %4f secs' % (f.__name__, end_time - start_time))
    return timer_wrap


@timer
def test_timer_func(num_times):
    """test_timer_func documentation """
    total_sum = 0
    for _ in range(num_times):
        total_sum += sum([i ** 2 for i in range(1000)])
    print('Total Sum: %f ' % total_sum)

@timer_wrap_with_functools
def test_timer_func_functools(num_times):
    """test_timer_func_functools documentation """
    total_sum = 0
    for _ in range(num_times):
        total_sum += sum([i ** 2 for i in range(1000)])
    print('Total Sum: %f ' % total_sum)


if __name__ == '__main__':
    print('------------------------------------')
    test_timer_func(200)
    print(test_timer_func.__name__)  #gives wrapper name
    print(test_timer_func.__doc__)   #gives wrapper name
    print('------------------------------------')
    test_timer_func_functools(200)
    print(test_timer_func_functools.__name__) #gives function name
    print(test_timer_func_functools.__doc__)  #gives function name
    print('------------------------------------')


# Output:
------------------------------------
inside timer_wrap decorator
Total Sum: 66566700000.000000
Total Time Taken by function test_timer_func is : 0.205079 secs
timer_wrap
timer_wrap documentation
------------------------------------
inside timer_wrap_with_functools decorator
Total Sum: 66566700000.000000
Total Time Taken by function test_timer_func_functools is : 0.188637 secs
test_timer_func_functools
test_timer_func_functools documentation
------------------------------------




No comments:

Post a Comment