Python · The language, not just syntax
Which Python profiling tools do you use and how do you read them?
Short answer
Use cProfile for deterministic function-level profiles, timeit for microbenchmarks, line_profiler for hot lines, and py-spy for sampling production processes without restarting them.
Deterministic profilers instrument calls and record every function invocation, which gives precise call counts and cumulative time but adds overhead. Sampling profilers periodically capture stacks, which is lighter and better for live processes.
import cProfile
import pstats
profiler = cProfile.Profile()
profiler.enable()
run_job()
profiler.disable()
stats = pstats.Stats(profiler)
stats.sort_stats("cumulative").print_stats(15)Reading a profile
- tottime is time in the function itself; cumtime includes callees
- High call counts with low time may indicate overhead rather than a target
- A function can be hot because of its own work or because of what it calls
- Use timeit for small isolated comparisons and repeat runs to reduce noise
Benchmark the operations that match production: same data size, same concurrency and same storage. A microbenchmark of a dict lookup rarely predicts end-to-end latency. Report percentiles, not just averages, because tail latency drives user experience.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the difference between tottime and cumtime?
- 2When would you use a sampling profiler instead of cProfile?
- 3How do you profile a running production process safely?
- 4Why are averages misleading in performance reports?
Say it in the interview
I use cProfile for deterministic function-level data, timeit for isolated comparisons, and py-spy when I need a sampling profile of a live process. I look at cumulative time to find expensive paths and self time to find where work happens, and I confirm hotspots with a second method. I benchmark realistic data sizes and report percentiles, because averages hide the tail latency that users actually feel.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Python mock interview and get scored feedback on depth, clarity and confidence.