Tips For Python

Ignacio Ruiz
2 min readJun 6, 2021

The one with cash

Welcome back! Today we’re gonna talk about a decorator that can help you speed up processes or functions in python.

Usually, when we create a function, we rely on the computational power to complete the process that we ask of it, whether it’s a mathematical process or a classification process we normally just call the function as many times as needed even though it might output the same result every time.

Here I will show you an easier way to speed up those processes and also help your computer out! We will use the functools library. We start by installing said library.

pip install functools

I got an error while using pip so I decided to install it through homebrew.

brew install functools

Homebrew is another installer, similar to pip, that can help you install python libraries and more.

Now that it’s installed, let’s begin! So, let’s look at an example of a computational taxing function. I created a function that calculates the Fibonacci number of each number provided. Where it’s computationally taxing it’s not only the calculation but as well you’re calling back on the same function making it harder to process.

As you can see, the function had to be stopped since by the time it was on its 39th iteration it had already taken 1 minute and 20 seconds. Way too long and my computer was starting to heat up.

But we can use functools to help us out. We will import func tools as well as the cache decorator.

from functools import lru_cache

Basically, what lru_cache does, it stores whatever computation it has been made, then there is no need for the computer to recalculate the process, it can just call back to whatever was already calculated. To use lru_cache all you have to do is call it before the function like @lru_cache and you’re done!

Let’s see how this function now compares.

Now would you look at that! just by using this simple decorator, the function took only 63 milliseconds to complete! Since the function didn’t need to recalculate previous numbers, it just needed to pull it from the cache!

And that is all! take a look and try it out!

--

--