Profiling and Optimization
Python Profilers and timeit
BOTIE
The documentation also separates profiling from benchmarking. A profiler instruments a program to locate costs; timeit supports focused timing experiments. The tools address different questions. Neither makes one workload or machine representative of every deployment.
Sources for this history
The Short Loop Was Not the Slow Part
Botie rewrites a small loop because it looks inefficient. The report barely changes speed. Repeated lookups elsewhere consumed most of the work, and the rewrite made the calculation harder to read.
We need to measure the operation that matters before choosing a repair, then check that the change preserves the report's meaning.
These measurements are invented and supplied. The blocks calculate estimates from them; they do not time Python. A real optimization also needs fresh measurements and unchanged behavior tests.
Step 1 of 1
Call count and call cost both matter
The supplied self costs exclude child work, avoiding overlap between these estimates.
| Operation | Calls | Self milliseconds per call |
|---|---|---|
| parse | 100 | 0.1 |
| lookup | 1000 | 0.02 |
| format | 1 | 5 |
parse
- Calls
- 100
- Self milliseconds per call
- 0.1
lookup
- Calls
- 1000
- Self milliseconds per call
- 0.02
format
- Calls
- 1
- Self milliseconds per call
- 5
Choose the cost you intend to reduce
The multiplication makes total cost visible. After source reads are reduced, the earlier slowest operation may no longer be the next useful target.
Find where the report spends its time
The report feels slow. The supplied profile records how often each operation ran and its mean time per call, excluding time in functions it called. That is self time. Many quick calls can cost less than a few slow ones.
BOTIE
Complete profile row with the largest estimated total self time
- operation
- Read source
- calls
- 40
- self_ms_per_call
- 5
Follow the operations
1. Recorded report operations and their costs
- operation
- Read source
- calls
- 40
- self_ms_per_call
- 5
- operation
- Format report
- calls
- 1000
- self_ms_per_call
- 0.1
- operation
- Validate records
- calls
- 40
- self_ms_per_call
- 0.2
operation calls self_ms_per_call Read source 40 5 Format report 1000 0.1 Validate records 40 0.2 2. Read a field from every record
- 040
- 11000
- 240
3. Read a field from every record
- 05
- 10.1
- 20.2
4. Multiply
- 0200
- 1100
- 28
5. Find the largest cost position
0
6. Retrieve one named position
- operation
- Read source
- calls
- 40
- self_ms_per_call
- 5
7. Result
- operation
- Read source
- calls
- 40
- self_ms_per_call
- 5
These measurements are invented and supplied. The blocks calculate estimates from them; they do not time Python. A real optimization also needs fresh measurements and unchanged behavior tests.
1. Choose the cost you intend to reduce
A response-time goal differs from a memory limit or a throughput target. Record the workload and constraint before changing code. A fast run on tiny input may miss the behavior that matters for a large report.
Establish a baseline on representative input. Keep correctness checks so a faster program cannot silently omit required work. Measure again under comparable conditions after the change.
2. Read call counts and costs together
A profile records calls and execution time. Self time excludes child work; cumulative time includes it. Adding the cumulative time of a caller and its child counts overlapping work twice.
A cheap operation repeated often can dominate one costly-looking call. The workshop multiplies supplied counts by supplied mean self costs to make this relationship visible. Actual profilers already report aggregated statistics.
parse: 100 × 0.1 ms = 10 ms
lookup: 1000 × 0.02 ms = 20 ms
format: 1 × 5 ms = 5 msThe lookup branch has the largest estimated self cost despite a small individual cost.
Check yourself
Questions on Parts 1 and 2
Question 1 of 2
What is the estimated total?
Question data
An operation runs 1000 times at a supplied mean self cost of 0.02 ms.3. Locate executed work with a profiler
cProfile can run a callable while recording its calls. pstats can organize those records by self or cumulative time. This example inspects a deterministic count instead of printing machine-dependent durations.
A profile describes the workload that ran and adds overhead. It may not account for work inside another process or a remote service. Keep end-to-end measurement separate when that is the application constraint.
Count calls during a controlled run
Inspect the entry for square itself, rather than variable-duration statistics.
import cProfile
def square(value):
return value * value
def report(values):
return sum(square(value) for value in values)
profiler = cProfile.Profile()
result = profiler.runcall(report, [2, 3, 4])
entry = next(item for item in profiler.getstats() if item.code is square.__code__)
print(result)
print(entry.callcount)29
3square ran once per supplied input. The count alone does not establish a system bottleneck.
4. Benchmark a repair without changing meaning
timeit repeats a focused operation to reduce the influence of one noisy timing. Include setup work when it belongs to the question. Benchmarking a lookup alone does not include building a large lookup table first.
A report-local cache can avoid repeated retrieval when the source is stable for that report. It changes meaning if values should change midway or the cache outlives the source version. Optimization therefore needs an explicit state lifetime.
A cached absence is still a result
Membership distinguishes saved None from a key that has not been queried.
cache = {"north": None}
print("north" in cache)
print(cache["north"])
print("south" in cache)True
None
FalseChecking cache.get(name) is None would confuse an already retrieved absence with an unqueried name.
5. Make local measurements reproducible
Use the actual project environment and representative inputs. Record enough context to repeat the measurement, including Python and relevant package versions. Repeat experiments and inspect variation rather than reporting one favorable result.
If a change does not improve the measured constraint, prefer clearer correct code. Caching, parallelism and compiled code have costs and assumptions of their own.
Run in your own environment
Two local measurement questions
These commands run in your own project environment. Their numeric timing output varies by workload and machine.
Replace report.py with the actual entry point and representative input.
Include setup inside the timed operation when it belongs to the question.
Compare equivalent operations under comparable conditions.
python -m cProfile -s cumulative report.py
python -m timeit -s "values = list(range(1000))" "sum(values)"The first command locates execution costs. The second measures a focused operation rather than the entire report.
Python profilers. Documentation checked .
Check yourself
Questions on Parts 1 to 5
Question 1 of 4
Which tool fits?
Question data
The question is which functions consume time in a representative report.Try it with Botie
Build with Botie
Write and run Python