The ULTIMATE Way to Make Your Python Code 100x FASTER!

def fib(n):
if n < 2:
return n
else:
return fib(n - 1) + fib(n - 2)
print(fib(10))
from time import perf_counterdef fib(n):
if n < 2:
return n
else:
return fib(n - 1) + fib(n - 2)
start = perf_counter()
print(fib(10))
end = perf_counter()
print(f"{end - start} seconds")
fib(5):
5
0.0004687000182457268 seconds
fib(10):
55
0.0004478000046219677 seconds
fib(20):
6765
0.0028874999843537807 seconds
fib(30):
832040
0.24202609999338165 seconds
fib(40):
102334155
34.25253349999548 seconds
from functools import wraps
from time import perf_counter
def fib(n):
if n < 2:
return n
else:
return fib(n - 1) + fib(n - 2)
start = perf_counter()
print(fib(10))
end = perf_counter()
print(f"{end - start} seconds")
from functools import wraps
from time import perf_counter
def memoize(func):
cache = {}
@wraps(func)
def wrapper(*args, **kwargs):
key = str(args) + str(kwargs)
if key not in cache:
cache[key] = func(*args, **kwargs)

return cache[key]
return wrapper
@memoize
def fib(n):
if n < 2:
return n
else:
return fib(n - 1) + fib(n - 2)
start = perf_counter()
print(fib(10))
end = perf_counter()
print(f"{end - start} seconds")
  • def memoize(): The memoize function has a function as a parameter (func) because it is a decorator.
  • cache: We start by creating a cache variable. This variable is self-explanatory, it will be storing any computation or result that has already been made, so we can reuse it instead and save a lot of memory and CPU time.
  • wrapper(*args, **kwargs): It’s getting a little bit out of scope so I will be saving it for a separate tutorial on how decorators work.
  • key: if the key (that we got from the function argument) does not already exist in our cache, we add it so we can use it later (keys in this case are the results of functions we used, using this decorator).
fib(5):
5
0.00036979999276809394 seconds
fib(10):
55
0.0003853000234812498 seconds
fib(20):
6765
0.0003789999755099416 seconds
fib(30):
832040
0.0004702000005636364 seconds
fib(40):
102334155
0.0005090999766252935 seconds
# Continuing just for the heck of it
fib(50):
12586269025
0.0005879999953322113 seconds
fib(100):
354224848179261915075
0.0008097999962046742 seconds

That’s 68504x faster!

If you need Django work, feel free to hire me at https://business.fiverr.com/share/YW9pAz

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Kaïss Bouali, ITIL™, Oracle Cloud Associate

Kaïss Bouali, ITIL™, Oracle Cloud Associate

A Python Software Engineer and Passionate Entrepreneur with 18+ years of experience in web development.