Profiling: distinguish calls, timing and allocation
性能分析基础
Measure a counting workload with separate profilers, timers and allocation traces, keeping setup and correctness explicit.
profilingA small function can repeat an expensive question
A feature pipeline counts how many times each sensor ID appears in an event archive. For every requested ID, it scans the whole archive again. The answer is right, and the counting function looks harmless. Repetition makes it expensive.
Before rewriting the pipeline, separate three questions: where does execution time go, how fast is a defined workload, and which allocations occur while it runs? Python provides different tools for these questions. A profiler locates work; a timer measures a specified experiment; allocation tracing observes a particular part of memory behavior.
Our experiment compares repeated scans, building a frequency index and querying it, and querying an already-built index. They return the same counts, but include different setup costs. Those boundaries are part of the result.
Measure the quantity your claim names
For event IDs x and requested ID q, the required feature is:
Two equal event IDs are two observations; replacing the archive with a set would lose counts. A frequency dictionary preserves them. For R events and Q queries, scanning takes O(RQ) work; constructing and querying the dictionary takes expected O(R+Q) work under ordinary hash-table assumptions. Keeping the index across several query batches changes how often its construction must be paid.
Find calls without treating the profiler as a stopwatch
cProfile records function calls and their execution statistics. In a usual profile table, tottime excludes subcalls, while cumtime includes them. Adding cumulative times of nested functions counts shared execution more than once. Here we extract the number of scan_one calls: 120 queries produce 120 calls, each scanning 1,000 events.
The Python profiler reference explicitly separates profiling from benchmarking. Instrumentation changes execution costs, particularly when comparing Python loops with C-level functions. This program runs its timer after the profile has stopped.
Time complete, named workloads
Each timing records three runs of one call, using timeit.Timer. scan includes every scan; build_and_query includes constructing a fresh Counter; query_existing_index excludes construction because its index already exists. Comparing the last two without naming that difference would misstate an end-to-end speedup.
The report retains raw seconds and their minimum. The timeit documentation explains interference, callable overhead and its default temporary disabling of cyclic garbage collection. The minimum is a useful low-interference observation for this setup, not a promised latency or a population percentile. Three short measurements are a teaching experiment; longer repeated runs and an explicit warm/cold policy are needed for a performance claim.
Trace allocations within a stated interval
tracemalloc reports currently traced bytes and the peak of traced bytes. It is not a measurement of process RSS or all native/GPU memory. Allocations made before tracing starts are outside this observation. See the tracemalloc reference.
Our two memory probes include scanning and building-plus-querying separately. Input tuples already exist before each trace. The returned list is kept alive until measurement, while a temporary Counter may already have been freed; peak and retained bytes therefore answer different questions. This probe refuses to replace an existing allocation trace and stops its own trace in a finally block.
Count first, measure second
Run this complete program with Python 3.12; it uses only the standard library. Event and query collections are lists or tuples of integer IDs from 0 to 1000, with at most 5,000 events and 200 queries. Booleans are rejected and empty inputs are valid. prepare validates once before timing; the internal counting functions operate on those validated tuples.
The fixture contains 1,000 events distributed evenly over 50 IDs. It requests IDs 0–59 twice. A hundred queries return 20 and twenty return zero, so the result sum is 2,000. That known answer is checked before interpreting any timing.
from collections import Counter
import cProfile
import json
import platform
import pstats
import timeit
import tracemalloc
def prepare(rows, queries):
for name, values, limit in [('rows', rows, 5000), ('queries', queries, 200)]:
if type(values) not in (list, tuple) or len(values) > limit:
raise ValueError(name + ' exceeds the list/tuple contract')
if any(type(v) is not int or not 0 <= v <= 1000 for v in values):
raise ValueError('integer event IDs in [0,1000] required')
return tuple(rows), tuple(queries)
def scan_one(rows, key):
total = 0
for value in rows:
if value == key:
total += 1
return total
def scan(rows, queries):
return [scan_one(rows, key) for key in queries]
def query_index(index, queries):
return [index.get(key, 0) for key in queries]
def build_and_query(rows, queries):
return query_index(Counter(rows), queries)
def traced_peak(work):
if tracemalloc.is_tracing():
raise RuntimeError('use this probe without another active allocation trace')
tracemalloc.start(1)
try:
baseline, _ = tracemalloc.get_traced_memory()
result = work() # Keep the returned list alive during measurement.
current, peak = tracemalloc.get_traced_memory()
return result, {'retained_bytes': current-baseline, 'peak_bytes': peak-baseline}
finally:
tracemalloc.stop()
def experiment(rows, queries):
rows, queries = prepare(rows, queries)
expected = scan(rows, queries)
index = Counter(rows)
if build_and_query(rows, queries) != expected or query_index(index, queries) != expected:
raise AssertionError('implementations disagree')
profiler = cProfile.Profile()
profiled_result = profiler.runcall(scan, rows, queries)
stats = pstats.Stats(profiler).stats
calls = sum(value[1] for key, value in stats.items() if key[2] == 'scan_one')
timing = {}
methods = {'scan': lambda: scan(rows, queries),
'build_and_query': lambda: build_and_query(rows, queries),
'query_existing_index': lambda: query_index(index, queries)}
for name, work in methods.items():
samples = timeit.Timer(work).repeat(repeat=3, number=1)
timing[name] = {'seconds': samples, 'minimum': min(samples)}
memory = {}
for name in ('scan', 'build_and_query'):
result, memory[name] = traced_peak(methods[name])
if result != expected:
raise AssertionError('allocation probe changed the answer')
return {'python': platform.python_version(), 'implementation': platform.python_implementation(),
'rows': len(rows), 'queries': len(queries), 'result_sum': sum(expected),
'results_equal': profiled_result == expected, 'scan_one_calls': calls,
'timing': timing, 'traced_memory': memory}
if __name__ == '__main__':
events = tuple(i % 50 for i in range(1000))
queries = tuple(i % 60 for i in range(120))
print(json.dumps(experiment(events, queries), indent=2, sort_keys=True))
One actual run is shown below. Timing and allocation numbers vary by interpreter, machine and concurrent work; they are not portable golden values. The counts and workload labels are deterministic.
{
"implementation": "CPython",
"python": "3.12.4",
"queries": 120,
"result_sum": 2000,
"results_equal": true,
"rows": 1000,
"scan_one_calls": 120,
"timing": {
"build_and_query": {
"minimum": 1.3249926269054413e-05,
"seconds": [
1.5249941498041153e-05,
1.3750046491622925e-05,
1.3249926269054413e-05
]
},
"query_existing_index": {
"minimum": 2.6670750230550766e-06,
"seconds": [
3.00002284348011e-06,
2.8330832719802856e-06,
2.6670750230550766e-06
]
},
"scan": {
"minimum": 0.0008344999514520168,
"seconds": [
0.0008545839227735996,
0.0008471249602735043,
0.0008344999514520168
]
}
},
"traced_memory": {
"build_and_query": {
"peak_bytes": 3496,
"retained_bytes": 1024
},
"scan": {
"peak_bytes": 1120,
"retained_bytes": 1024
}
}
}
The fastest query-only number does not include the existing index’s construction or retained storage. If an application rebuilds the index for every single query, that is a different workload from reusing it for an entire batch. Report the behavior your application actually performs.
This experiment profiles calls, times unprofiled functions, and traces allocations in separate executions. It does not measure elapsed time with every instrument turned on at once. Validation and fixture creation are outside the timing interval; adding them is necessary when the desired quantity is total pipeline latency.
A local speedup has a limited effect on the whole pipeline
Suppose this counting stage consumes fraction f of the original total runtime. Even making it instantaneous can improve the whole pipeline by at most:
The remaining fraction still takes time. If counting consumes 20%, the ceiling is 1.25 times faster under the assumption that other stages stay unchanged. This is why a convincing microbenchmark can coexist with an unimpressive application result.
Caching can shift work and memory rather than remove them. Establish the cache lifetime, invalidation rule, construction cost and retained size. Also preserve semantics: missing IDs, duplicates and output order are part of this feature’s contract.
This example does not benchmark file I/O, network calls, multiple workers or accelerators. Device work may be asynchronous, so host-call duration alone may exclude completion; use the relevant device’s supported synchronization and profiling tools when extending the experiment. Do not label these CPU measurements as GPU results.
Tests check answers, call counts, report structure and tracing cleanup. They deliberately do not require a particular number of seconds, byte count or winner. A slower run under background load is not automatically an algorithm regression.
Audit the measurement boundary
- An archive contains
[7,7,9], and queries are[7,8,7]. What must each method return?
Answer: [2,0,2]. A set would incorrectly lose multiplicity; sorting queries could change output order.
- Why does querying an existing index not establish the speed of rebuilding that index for every request?
Answer: Construction is outside the measured call. Time construction plus querying, or measure the actual reuse lifetime separately and include both costs in the application estimate.
- Can low retained traced memory prove that the operation had low peak memory?
Answer: No. Temporary allocations can be freed before the result is inspected. The peak can be much larger, and pre-existing or untraced allocations are outside both reported numbers.
- Counting takes 20% of total time. What happens to the total-time ceiling if counting becomes infinitely fast?
Answer: The other 80% remains, giving a maximum speedup of 1/0.8=1.25 under unchanged surrounding work. It does not make the whole pipeline infinitely fast.
Keep measurement tools in their proper roles
The Python profiler, timeit and tracemalloc references describe what their observations include. Read those boundaries before turning measurements into claims. The frequency-index example is original; no upstream benchmark, dataset or code was copied.
Continue with algorithmic complexity, vectorization and parallel computing. Measure after establishing correctness, then recheck the complete workload after an optimization.
Make a prediction, then check
Which timing includes a fresh frequency-index construction?
Learning objectives
- Separate profiling, timing and allocation observations.
- Include index construction when defining an end-to-end comparison.
- Check semantics and measurement boundaries without fixing timing winners.
Prerequisites & connections
Explore related knowledge →References
- The Python Profilers — Python 3.12
Python Software Foundation - timeit — Measure execution time of small code snippets — Python 3.12
Python Software Foundation - tracemalloc — Trace memory allocations — Python 3.12
Python Software Foundation
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-agent authored technical review: primary-source locations, derivations, literal or exact computational checks, real runtime experiments where stated, and bilingual review; not independent human or second-agent peer review.
- Five tests passed; measured counts and timing/allocation structure, without asserting a speed winner. Strict bilingual rendering: two formulas, six anchors and four answers.
- Single-agent authored technical review, with primary-source locations, stated assumptions and matching bilingual examples/exercises. Not independent human or second-agent review. Final publication navigation and repository checks are separate.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- The Python Profilers — Python 3.12 · Read profiling-versus-benchmarking warning line 17 and total/cumulative time definitions; inspected actual Stats call-count output.
- timeit — Measure execution time of small code snippets — Python 3.12 · Read callable overhead line 68, temporary GC disabling line 76, repeat semantics 89–94, minimum and full-vector interpretation 97–98.
- tracemalloc — Trace memory allocations — Python 3.12 · Read current/peak traced blocks 249–252, stop/clear behavior 290 and pre-trace allocation exclusion 300.
Related topics