Skip to content

Instantly share code, notes, and snippets.

@favtuts
Last active February 23, 2022 08:30
Show Gist options
  • Save favtuts/dd84f98399426c721a41224f48d76926 to your computer and use it in GitHub Desktop.
Save favtuts/dd84f98399426c721a41224f48d76926 to your computer and use it in GitHub Desktop.
Python cache using LRU_cache from functools standard library. More details on blog post: https://www.favtuts.com/every-python-programmer-should-know-lru_cache-from-the-standard-library/
from functools import lru_cache
from datetime import datetime
@lru_cache(maxsize=None)
def fib_cache(n):
if n < 2:
return n
return fib_cache(n-1) + fib_cache(n-2)
def fib_no_cache(n):
if n < 2:
return n
return fib_no_cache(n-1) + fib_no_cache(n-2)
def timeit(func,samples):
start = datetime.now()
func(samples)
end = datetime.now()
return end-start
UPPER = 40
print("calculating fibonaci using cache...")
cached = []
for i in range(0,UPPER):
cached.append(timeit(fib_cache,i))
print(*(str(x) for x in cached), sep=",")
print("calculating fibonaci without cache...")
not_cached = []
for i in range(0,UPPER):
not_cached.append(timeit(fib_no_cache,i))
print(*(str(x) for x in not_cached), sep=",")
'''
Install pandas and seaborn
pip install matplotlib
pip install pandas
pip install seaborn
'''
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
print("generating seaborn ...")
_ = pd.DataFrame([cached,not_cached]).T
_.columns = ['cached','not_cached']
_ = _.applymap(lambda x: x.value/1000000000)
sns.set()
g = sns.lineplot(data=_)
g.set_ylabel('time in seconds')
g.set_xlabel('samples')
plt.show()
print("generated graph ...")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment