Sobes.tech
Junior — Middle

Have you ever had situations where you needed to improve the performance of a Python program?

sobes.tech AI

Answer from AI

Yes, to improve the performance of Python programs, several approaches are often used:

  • Code profiling using modules like cProfile or timeit to identify bottlenecks.
  • Algorithm and data structure optimization — replacing inefficient algorithms with faster ones.
  • Using built-in functions and libraries — they are usually implemented in C and run faster.
  • Caching results with functools.lru_cache for expensive computations.
  • Parallelization and multithreading — considering GIL limitations, for example, through multiprocessing.
  • Using compiled extensions — such as Cython or PyPy.

An example of using lru_cache to speed up a recursive function:

from functools import lru_cache

@lru_cache(maxsize=None)
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(30))