Patternite Logo

Timing functions with Python decorators


Using python decorators we can easily profile the execution time of functions


Python decorators provide a clean syntax for adding extra functionality to functions. Here we're interested in logging the execution time of the functions in our program. We create a defaultdict called timings on line #7. This is identical to a regular Python dictionary, except it will initialize default values to an empty array [] when non-existent keys are accessed, rather than throwing a KeyError.

Our timer decorator works by tracking the start_time and end_time of function's execution, and then stores the difference (i.e. the total time) in timings. To properly identify the function that was profiled, the key passed to timings is the __name__ property of function.

Then, to profile a function, we can simply decorate it with @timer. Whenever this function runs, the execution time will be logged in our timings dictionary.

This Stack Overflow question has a great discussion about decorator usecases.

Profile picture for duncster

| edited

Patternite © 2021

Patternite Logo