Profiling and Performance Decisions
Measure a real workload before choosing an optimisation.
python, profiling, performance, timeit, cprofile, memoryMeasure the real question
Performance depends on the workload, environment, and cost being measured. Start with a correctness test and a representative input, locate the bottleneck, change one thing, and compare again. A small benchmark alone does not predict every production workload.
Python illustration
import cProfile
import pstats
import io
def total(values):
return sum(values)
profile = cProfile.Profile()
answer = profile.runcall(total, [2, 4, 3])
report = io.StringIO()
pstats.Stats(profile, stream=report).sort_stats("cumulative").print_stats()
print(answer)
print("total" in report.getvalue())
Prepared output — not live execution:
9
True
The profiler observes a single tiny call; the exact timing and call counts depend on the interpreter and environment. The report can identify where time was spent, not guarantee that this function is a real-world bottleneck.
See the reasoning
Follow a measurement
Distinguish a measured call from a performance claim. This is a prepared demonstration, not live code execution.
Choose the workload
- Workload[2, 4, 3]Current focus
- Profilenot run
- Reportpending
- Conclusionnot established
This example profiles one call with [2, 4, 3].
Choose the right measurement
timeit repeats a small operation to help compare alternatives; include
setup, input size, interpreter, and repeated measurements when interpreting
results. It disables garbage collection by default during timing, which can
matter for some workloads. tracemalloc can compare snapshots of traced
Python allocations after tracing starts, but does not capture all native
or external memory. Avoid exposing sensitive data in profiling output.
Algorithmic complexity, data layout, I/O, and concurrency can dominate micro-optimisations. Use realistic inputs and budgets, measure before and after, check edge cases, and keep the clearer solution when performance does not justify extra complexity.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
