How to measure the execution time of Python function

In this code sample, we will see how to measure the execution time of python functions. 




	

from functools import wraps
from time import time, sleep

def timeit(func):
    '''A simple time calculator decorator'''
    @wraps(func) # preserves the metadata like docstring of the function
    def wrapper(*args, **kwargs):
        start_time = time()
        result = func(*args, **kwargs)
        end_time = time()
        print(f'Function {func.__name__} exectued in {(end_time - start_time):.4f}s')
        return result
    return wrapper

@timeit
def get_files_from_hdfs():
    sleep(2)
    print('Done!')

if __name__ == '__main__':  
    get_files_from_hdfs()
    

Post a Comment

0 Comments