lru_cache() reducing the execution time

 Tips: lru_cache on a method uses separate storage for each instance of the class and reduces the execution time. inherited from "functools"

Example 1. 


def increment(num):
    print(f'Running thousands line of code {num}')
    return num + 1

print(increment(1))
print(increment(2))
print(increment(3))
print(increment(1))

output :
Running thousands line of code 1 2 Running thousands line of code 2 3 Running thousands line of code 3 4 Running thousands line of code 1 2

Note : increment(1)
a function is called 2 times at the same time and it could increase the execution
time. and we can reduce the execution time and their process with the help of the
lru_cache method

Modified version :

from functools import lru_cache
@lru_cache # a type of decorators
def increment(num):
   
    print(f'Running thousands line of code {num}')
    return num + 1

print(increment(1))
print(increment(2))
print(increment(3))
print(increment(1))

output :

Running thousands line of code 1 2 Running thousands line of code 2 3 Running thousands line of code 3 4 2 ⇠

Observed that 2 returns from the cache not from the function


Caution :

Using functools.lru_cache can cause memory leaks if it's used incorrectly, especially when applied to instance methods of a class.

I will make a separate post for incorrectly used and memory leaks :)







Comments