Write a function to print the time it takes to run a function


Topic: Write a function to print the time it takes to run a function

Solution

import time
def time_it(fn, *args, repetitons= 1, **kwargs):
    start = time.perf_counter()
    if (repetitons <= 0):
        raise ValueError("repetitions should be greater that 0")
    if (not(isinstance(repetitons,int))):
        raise ValueError("Repetions must be of type Integer")
    for _ in range(repetitons):
        fn(*args, **kwargs)
    stop = time.perf_counter()
    return ((stop - start)/repetitons)



List all Python Programs