Function Caching in Python

    

   import time
from functools import lru_cache

@lru_cache(maxsize=1)
def add_work(n, m):
    time.sleep(3)
    return n + m

print(add_work(3,4)) # takes 3 secs to print
print(add_work(3,5)) # takes 3 secs to print
print(add_work(3,4)) # takes 3 secs to print
print(add_work(3,5)) # takes 3 secs to print
print(add_work(3,5)) # this and rest takes no time to print
print(add_work(3,5))
print(add_work(3,5))
print(add_work(3,5))

###############################################3
# Following takes user input for defining maxsize

import time
from functools import lru_cache

@lru_cache(maxsize=int(input("Enter maxsize for lru_cache: ")))
def some_work(n, m):
    time.sleep(3)
    return n + m

print(some_work(3,4))
print(some_work(3,5))
print(some_work(3,4))
print(some_work(3,5))
print(some_work(3,4))
print(some_work(3,5))

    

Comments

Popular posts from this blog

Quotation marks to wrap an element in HTML

The Basic Structure of a Full-Stack Web App

Unlocking Web Design: A Guide to Mastering CSS Layout Modes