Profiling Python
- Profile before touching. A profiler like cProfile shows where time actually goes: intuition about hotspots is usually wrong.
- Line-level timing. Once a hot function is known, line profiling or timeit pins the exact statement worth attention.
- Measure the real workload. Profile the real workload: a toy benchmark optimises a program you do not actually run.
Memory and CPU Optimisation
- Right data structures. Most Python speedups are structural: a set membership test beats scanning a list a thousand-fold.
- Slots. Declaring __slots__ removes the per-instance dict, shrinking millions of small objects dramatically.
- Batch the boundary. Crossing into C: numpy, the database, the network: is costly per call: batch work into fewer, bigger crossings.
Native Extensions and Performance Boundaries
- C extensions. Heavy libraries run their inner loops in C: Python orchestrates, native code computes.
- When Python is enough. Most services wait on the network, not the CPU: rewriting those in a faster language buys nothing.
- Escape hatches. When CPU truly binds, options climb: better algorithm, Cython or native modules, or a service in another language.
Before and after this level
- Before: Level 14: Python Internals: Object Model and Data Model, Magic Methods and Descriptors, Interpreter and Garbage Collection.
- Next: Level 16: Packaging & Production Python: Packaging and Distribution, Configuration, Logging and Environments, Production-Grade Python Design.
In the app each of these ideas is taught and then asked back, and the level ends with a checkpoint and flashcards. See Checkpoints and flashcards.
Frequently asked questions
What does Python Level 15: Performance cover?
Profiling Python, Memory and CPU Optimisation, Native Extensions and Performance Boundaries: 3 lessons and 9 ideas.
What should I know before this level?
The level before it, Level 14: Python Internals, which covers Object Model and Data Model, Magic Methods and Descriptors, Interpreter and Garbage Collection.