Use a decorator

Let's see how we can write our own decorator and create a timing context manager.

We'll cover the following...

Writing our own timer is a lot of fun too, although it may not be as accurate as just using timeit depending on the use case. Regardless, we’re going to write our own custom function timing decorator! Here’s the code:

Press + to interact
import random
import time
def timerfunc(func):
"""
A timer decorator
"""
def function_timer(*args, **kwargs):
"""
A nested function for timing other functions
"""
start = time.time()
value = func(*args, **kwargs)
end = time.time()
runtime = end - start
msg = "The runtime for {func} took {time} seconds to complete"
print(msg.format(func=func.__name__,
time=runtime))
return value
return function_timer
@timerfunc
def long_runner():
for x in range(5):
sleep_time = random.choice(range(1,5))
time.sleep(sleep_time)
if __name__ == '__main__':
long_runner()

For this example, we import the random and the time modules from Python’s standard library (Lines 1-2). Then we create our decorator ...