🐍 Python for Everyone

← Back to interview questions

Chapter 25 Project 50 min build

Memory Profiler for an Earlier Project

A small, standalone memory profiler that instruments any zero-argument function with tracemalloc, reporting peak memory use and top allocations — then uses it to run a real before/after comparison between a memory-heavy version and a memory-optimized version of the same logic.

Example run

Output
=== Memory Profiler Report ===

--- heavy (list) ---
Peak memory: 1,109,728 bytes
Top allocations:
  solution.py:62: size=17.3 KiB, count=255, average=70 B
  solution.py:78: size=64 B, count=2, average=32 B
  solution.py:22: size=64 B, count=2, average=32 B

--- optimized (generator) ---
Peak memory: 408 bytes
Top allocations:
  (none traced -- this version never held more than the interpreter's own baseline at once)

Smaller peak memory: optimized (generator)

Your own exact byte counts and line numbers will differ slightly by Python version/platform — the comparison is the point, not memorizing one number.

How to run Download starter.py below into an empty folder, then run python3 starter.py. Standard library only — no installs needed.

The core piece: profile_function()

Everything else in this project calls this one reusable function — it's the actual "profiler" part.

profile_function.py
import tracemalloc


def profile_function(func):
    tracemalloc.start()
    result = func()
    current, peak = tracemalloc.get_traced_memory()
    snapshot = tracemalloc.take_snapshot()
    tracemalloc.stop()

    top_stats = snapshot.statistics("lineno")
    top_allocations = [
        {"location": str(stat), "size_bytes": stat.size, "count": stat.count}
        for stat in top_stats[:3]
    ]

    return {
        "result": result,
        "current_bytes": current,
        "peak_bytes": peak,
        "top_allocations": top_allocations,
    }

Thought process: a reusable profiler has to accept an arbitrary zero-argument callable, not a hardcoded function name, so it can be pointed at anything later — that's why func() is called generically inside, and why the snapshot is taken right after the call (while the peak is still meaningful) rather than after some later cleanup step that could distort the reading.

Write the prompt you'd give an AI assistant to build this:

Show a strong version of this prompt
Write a Python function called profile_function(func) using only the standard library tracemalloc module. It should accept any zero-argument callable, start tracemalloc, call func(), read current and peak memory with get_traced_memory(), take a snapshot with take_snapshot() BEFORE stopping tracemalloc (a snapshot taken after stop() will be empty), then stop tracing. Return a dict with keys "result" (func()'s return value), "current_bytes", "peak_bytes", and "top_allocations" — a list of the top 3 entries from snapshot.statistics("lineno"), each as a dict with "location" (str(stat)), "size_bytes" (stat.size), and "count" (stat.count).

The pieces

Ideas to make it your own

Why this project matters

"Is this actually lighter, or does it just feel like it should be?" is a question real engineers answer by measuring, not guessing — this project builds a small, reusable tool for doing exactly that, on any function, not just the one example built here.

More project ideas

From Chapter 7 onward, you get a genuine choice of what to build. The Memory Profiler above is fully built out with a starter and reference solution — the four ideas below are not. Each is a real, grounded use case solvable with only what's been taught through Chapter 25. No starter or solution files are provided on purpose — building one of these unassisted is the point.

1 A Data-Structure Memory Comparison Tool

Problem: The same dataset can be stored as a list of tuples, a list of dicts, or a list of __slots__-based objects — which one actually uses the least memory?

What it should do: Build the same 10,000-row dataset three ways and report each structure's peak memory via tracemalloc, ranked smallest to largest.

Suggested approach: Reuse this project's profile_function() directly — this is almost the same tool, pointed at three build functions instead of two.

2 A __slots__ Refactoring Exercise

Problem: A provided class with 5+ attributes and no __slots__ needs refactoring, and someone wants to know exactly how much memory that refactor actually saves at scale.

What it should do: Take a class, build 10,000 instances of both the original and a slotted version, and report the total memory difference.

Suggested approach: Sub-topic 4's PointRegular/PointSlotted comparison, scaled up to a realistic instance count.

3 A Reference-Cycle Detector

Problem: Given a small object graph (nodes with .next/.parent attributes), detect whether it contains a reference cycle before it ever becomes a real memory problem.

What it should do: Walk the object graph from a starting node, tracking visited object ids, and report True/False for whether a cycle exists.

Suggested approach: A visited-set walk using id() to track already-seen objects, similar in spirit to graph traversal.

4 A "Memory Leak" Bug Hunt with weakref

Problem: A provided class has an intentional memory leak — a cache dict that holds strong references to objects long after they should be collectable.

What it should do: Diagnose why instances aren't being freed even after all "real" references are dropped, then fix it using the weakref module.

Suggested approach: Reproduce the leak first with gc.collect() showing 0 freed, then swap the cache's strong references for weakref.WeakValueDictionary.

← Interview Questions Now Pair With an AI →