Sometimes, however, manually inserting the last code can be somewhat of an overkill, and may end up bloating your codebase when it's unnecessary. Thankfully, Python offers a solution to this.
We can define our own decorator function, which will automatically wrap our function's execution with two calls to timeit.default_timer(). We'll then retrieve the differences between these two calls and display this on the console.
import random
import timeit
import time
def timethis(func):
def function_timer(*args, **kwargs):
start_time = timeit.default_timer()
value = func(*args, **kwargs)
runtime = timeit.default_timer() - start_time
print("Function {} took {} seconds to run".format(func.__name__, runtime))
return value
return function_timer
@timethis
def long_runner():
for x in range(3):
sleep_time = random.choice(range(1,3))
time.sleep(sleep_time)
if __name__ == '__main__':
long_runner()
This preceding code will print out any function we pass into it with the exact time it took to run it. When you run it, you should see the following output on the console:
$ python3.6 05_timeitDecorator.py
Function long_runner took 5.008787009981461 seconds to run