In this lesson, you’ll see how to use decorators to measure the time a function takes to execute and print the duration to the console.
Timing Functions With Decorators
For this first example, I’ll have you create a decorator that can time functions and how long it takes for them to run. To start this process, back in the editor, inside the module
decorators.py, copy the boilerplate and paste it a little bit lower in the code.
and then end that also with triple quotes. So,
timer() takes a function into it, this is its docstring. Then it’s decorated with
@functools.wraps(). Instead of
wrapper_decorator, it’s going to be the
And then something we’ll do here, you will assign a
start_time by using the method from
perf_counter() and calling it. I’ll leave a note here that it’s the first step that’s new outside of renaming.
And save. Okay, so here it is: your decorator that will time functions, that you just built. You can remove this additional comment. Looks good! So, when the function is called, it’s passed into here, a
start_time is calculated, the function runs. When the function has been called and is completed, an
end_time is generated.
run_time is calculated by subtracting the start out of the end time, and then to the console is printed a statement
f"Finished", our function’s
.__name__—and that’s good that we have our
functools—and then the
run_time, and then the
value is returned. Great! Okay. Again, make sure you have saved, then back in
examples, change your
I’ll leave it showing here in the background. Okay. Time to waste some time. How to do that? Go ahead and re-enter into your REPL. Mine’s
bpython again. Yours could be just typing
You need to import
waste_some_time(). To do that,
from examples, simply do that:
import waste_some_time. Please make sure that you’re still in the
decorators/ folder that has these two modules inside of it. Okay.
05:28 Okay. That took a bit longer, almost two and a half seconds. Decorators are pretty advanced. It’s good to practice visually stepping through all the stages of your decorator. This next example will help with that even more.
Become a Member to join the conversation.