Python Master Course V2 — 108. Profiling Time and Memory
SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 11 · LESSON 108 OF 200
Profiling Time and Memory
Study: 90–120 minutes · Prerequisites: Lessons 101–102, functions, classes, exceptions and tests.
Video lesson
Video not yet available. A verified video URL/player will be added when supplied.
Learning outcomes
Explain profiling time and memory, reason about runtime behavior, apply the technique in a maintainable program, and test normal, boundary and invalid inputs.
Understand and apply: Profiling Time and Memory
Measure realistic workloads before optimizing. perf_counter measures elapsed time; tracemalloc observes Python allocations, while sys.getsizeof only measures shallow object size.
Ask a measurement question before changing code
Timing answers how long a defined workload takes; profiling helps locate where that time or memory is spent. First state the workload, its size and the result that must remain unchanged. Compare equivalent work with fresh inputs, warm up once if appropriate, and record Python version, implementation, operating system and machine. A faster run that skipped half the input is not an optimization.
perf_counter measures elapsed duration using a high-resolution clock; its absolute value is not a wall-clock timestamp. timeit repeats a small callable and helps reduce one-off measurement mistakes. Divide a batch duration by the number of calls to estimate time per call. Repeated minima can indicate an unobstructed lower bound, while the full range shows noise; neither predicts every production request’s latency.
Python example
import platform
import sys
import timeit
import tracemalloc
def list_total(n):
return sum([value * value for value in range(n)])
def stream_total(n):
return sum(value * value for value in range(n))
def peak_bytes(function, n):
tracemalloc.start()
try:
result = function(n)
current, peak = tracemalloc.get_traced_memory()
return result, peak
finally:
tracemalloc.stop()
n = 100_000
expected = n * (n - 1) * (2 * n - 1) // 6
assert list_total(n) == stream_total(n) == expected
print("Result:", expected)
print("Environment:", platform.python_implementation(), sys.version.split()[0])
for function in (list_total, stream_total):
function(n) # Unmeasured warm-up.
samples = timeit.repeat(lambda: function(n), repeat=5, number=3)
result, peak = peak_bytes(function, n)
assert result == expected
print(function.__name__, "seconds/call:", min(samples) / 3,
"peak traced bytes:", peak)
Expected output
Result: 333328333350000
Environment: <implementation> <Python version>
list_total seconds/call: <measured value> peak traced bytes: <measured value>
stream_total seconds/call: <measured value> peak traced bytes: <measured value>
The first output line is exact. Version, durations and byte counts must come from the learner’s own run. Both functions square and sum the same range. list_total retains all squares until sum finishes, whereas stream_total supplies one square at a time. Expect a substantial difference in retained intermediate data; do not promise that the generator will be faster, because iteration and allocation costs differ by implementation and workload.
Measure allocations while the temporary data exists
tracemalloc records traced Python memory allocations after tracing starts. Current usage after a function returns can miss a large temporary list that has already been released, so this experiment reports peak traced bytes. It is not the process’s total resident memory and may exclude allocations performed directly by native libraries. Starting and stopping tracing around each measurement separates the two runs; this helper assumes no other tracing session needs to remain active.
sys.getsizeof measures an object’s shallow size. For a list it does not recursively add the size of all referenced values. Summing nested sizes naively can also double-count shared objects. Use shallow size to answer a shallow question, allocation tracing to investigate Python allocations, and an appropriate process-level tool when total process memory is the actual constraint.
Find a time hotspot before optimizing it
Python example: run after the workload definitions
import cProfile
import pstats
profiler = cProfile.Profile()
profiler.runcall(list_total, 100_000)
pstats.Stats(profiler).strip_dirs().sort_stats("cumulative").print_stats(5)
The profiler output contains machine-dependent call counts and durations. cumtime includes time in callees; tottime focuses on a function’s own work. Use this to identify a candidate hotspot, then benchmark a proposed change without profiler overhead. Do timing and allocation experiments separately because instrumentation changes the workload.
For the project, repeat both implementations at several n values, confirm equality before comparing metrics, and save the environment plus raw samples. A generator object’s shallow size alone does not measure pipeline memory. The consumer, current record, accumulated integers and any retained logs all matter. A fixed number of live objects is a more precise claim than identical memory usage at every input size.
Progressive runnable examples
Requires Python 3.10+. Save as lesson108.py and run python lesson108.py or python3 lesson108.py. Expected outputs below are illustrative and not claimed to have been executed on Smartyfy.
Example 1 — Core mechanism
import sys
small = [0] * 10
large = [0] * 100
print(len(small), len(large))
print(sys.getsizeof(large) > sys.getsizeof(small))
Expected output:
10 100
True
Guided practical project
Project: Compare list materialization against a generator pipeline with tracemalloc and repeatable inputs.
Use the complete implementation and explicit contract in the worked explanation above. Reproduce its deterministic sample, test the stated boundary and failure cases, and explain the documented limitations before adapting it.
Common mistakes and debugging
- Adding abstraction without a demonstrated need.
- Hiding state or unexpected side effects.
- Assuming type hints replace validation.
- Ignoring resource cleanup or error propagation.
- Measuring performance on unrepresentative data.
- Failing to test boundary and error cases.
Debug by reproducing the smallest failing input, inspecting the traceback and intermediate values, then adding a regression test.
Practice with explained answers
Predict each result before opening the answer. Explain how the design handles both ordinary and boundary cases.
Why assert equal results before comparing timings?
Otherwise one implementation might do less work or produce a wrong answer. The shared closed-form sum gives an independent expected value, so the benchmark compares two correct implementations of the same workload.
Why divide the minimum timeit result by three?
number=3 means each recorded sample is a batch of three calls. Dividing converts the batch duration to an estimated duration per call. repeat=5 produces five such batches; it does not mean each sample already represents one call.
Why report peak rather than current traced memory?
The materialized list can disappear before the function returns. Current allocations may therefore look small even though a large temporary existed. Peak records the highest traced usage during the measurement interval.
Does getsizeof(a_list) include every element’s full size?
No. It describes the list object’s shallow allocation, including its references on typical implementations. The referenced objects may exist separately or be shared. Recursive totals require a defined ownership and deduplication policy.
Is the lowest observed time a guarantee for production?
No. It is useful as an approximate lower bound under the measured conditions. Real latency also depends on input variation, contention, I/O and system load. Keep the raw distribution and use representative workloads.
What does a high cumulative time but low own time suggest?
The function spends much of its total duration in callees. Inspect those callees rather than rewriting the outer function blindly. Recheck correctness and benchmark without profiling instrumentation after a candidate change.
Mastery checkpoint
Explain the concept without notes, reproduce the core example, finish the project, run three tests and justify when the technique is appropriate. No account-synced completion or certification is claimed.
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.