Skip to content

Add a command-line interface to tracemalloc #159560

Open

Description

@vadim-smal

Feature or enhancement

Proposal:

Today, to check memory allocations of a script with tracemalloc you have to modify the script itself: call tracemalloc.start(), take a snapshot at the right place, then print the statistics. For simple cases I think it would be convenient to run it the same way as cProfile, without touching the code:

python -m tracemalloc [-o OUTFILE] [-t {filename,lineno,traceback}] [--cumulative]
                      [-n NFRAME] [-l LIMIT] (-m module | script.py) [args ...]

Tracing starts right before the program runs. When it exits, a snapshot is taken and the top allocations that are still alive get printed, plus the total and the peak traced size:

$ python -m tracemalloc -l 5 script.py
Top 5 lineno allocations still alive at exit:
script.py:2: size=981 KiB, count=101, average=9942 B
<frozen runpy>:266: size=434 B, count=4, average=108 B
<frozen runpy>:102: size=400 B, count=1, average=400 B
<frozen runpy>:81: size=400 B, count=1, average=400 B
script.py:1: size=168 B, count=1, average=168 B
2 other: size=90 B, count=2
Total size: 982 KiB
Peak size: 983 KiB

Options:

  • -o OUTFILE dumps the snapshot instead of printing it, so it can be loaded later with Snapshot.load() ( same idea as cProfile -o )
  • -t key type for Snapshot.statistics(), lineno by default
  • --cumulative cumulative mode of Snapshot.statistics()
  • -n max number of frames, same as tracemalloc.start(nframe)
  • -l number of statistics to display, 10 by default
  • -m run a module, like python -m

The traced program gets the same sys.argv, __name__ and sys.path[0] as when it runs directly. Memory freed before exit only shows up in the peak size.

Has this already been discussed elsewhere?

I have already discussed this feature proposal on Discourse

Links to previous discussion of this feature:

https://discuss.python.org/t/run-tracemalloc-module-as-a-script/50821 ( Marc-André Lemburg suggested to submit a PR )

Linked PRs

Activity

  1. added
    type-featureA feature request or enhancement
    stdlibStandard Library Python modules in the Lib/ directory
    on Oct 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-featureA feature request or enhancement

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions