How do you profile and speed up slow Python code?

Python advanced features · Experienced

Model answer

Measure first with cProfile or a sampling profiler such as py-spy, and timeit for small pieces. Then fix the biggest cost: better algorithms and data structures, fewer repeated calculations (caching), built-ins and comprehensions, NumPy for numeric work, multiprocessing for CPU-bound tasks, or moving a hot loop to a compiled extension.

Learn this topic

The Python Standard Library: Dates, Counter, Statistics and More in the course Python for Beginners: Learn to Code with Real Projects.

Sign in to add your own answer.

More questions