# 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):50.0004687000182457268 secondsfib(10):550.0004478000046219677 secondsfib(20):67650.0028874999843537807 secondsfib(30):8320400.24202609999338165 secondsfib(40):10233415534.25253349999548 seconds`
`from functools import wrapsfrom 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")`
`from functools import wrapsfrom time import perf_counterdef 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@memoizedef 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):50.00036979999276809394 secondsfib(10):550.0003853000234812498 secondsfib(20):67650.0003789999755099416 secondsfib(30):8320400.0004702000005636364 secondsfib(40):1023341550.0005090999766252935 seconds# Continuing just for the heck of itfib(50):125862690250.0005879999953322113 secondsfib(100):3542248481792619150750.0008097999962046742 seconds`

# That’s 68504x faster!

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

--

--

## More from Kaïss Bouali, ITIL™, Oracle Cloud Associate

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

Love podcasts or audiobooks? Learn on the go with our new app.

## Kaïss Bouali, ITIL™, Oracle Cloud Associate

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