tracemalloc Snapshots Allocation Hotspots
Start tracemalloc, snapshot before and after building an index, compare allocation sites by line, and read current versus peak memory.
Code
import tracemalloc
def build_index(rows: int) -> dict[int, str]:
return {row: 'user-' + str(row) for row in range(rows)}
def main() -> None:
tracemalloc.start(10)
first = tracemalloc.take_snapshot()
index = build_index(20_000)
second = tracemalloc.take_snapshot()
for stat in second.compare_to(first, 'lineno')[:3]:
print('size diff:', stat.size_diff, 'count diff:', stat.count_diff)
current, peak = tracemalloc.get_traced_memory()
print('current bytes:', current)
print('peak bytes:', peak)
print('index entries:', len(index))
tracemalloc.stop()
if __name__ == '__main__':
main()How it works
tracemalloc Snapshots Allocation Hotspots is built around the functions build_index and main.
Iteration happens inside for stat in second.compare_to(first, 'lineno')[:3] — everything outside it runs once.
What comes back is a new object, not a reference to anything passed in.
What to watch for
- Dependency check:
tracemalloc— not built-in, must be present in the project.
Putting it to use
The primary signature is def build_index(rows: int) -> dict[int, str]
The demo output is labeled (size diff:, current bytes:, peak bytes:), so every printed line maps back to its originating operation.
The demo flow inside main is build_index — run the file to see it end to end.
Core lines
return {row: 'user-' + str(row) for row in range(rows)}
Interactive Tools for This Topic
FAQ
- Does `build_index` modify its input?
- No mutation happens — the function reads its input and returns a new value.
- Does this require external packages?
- Yes — `tracemalloc`. Add it to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.