5.4. Profiling Tracing

  • Deterministic profiler

  • Deterministic tracing

  • profiling.tracing

  • Tracing profilers record every function call and return, which can be very slow and produce large amounts of data.

  • Best for exact function-call counts, call graphs and detailed function-level execution analysis.

Unlike sampling, deterministic tracing records every function call, return and exception event.

This provides exact call counts, but introduces execution overhead.

5.4.1. Profile Script

$ python -m profiling.tracing myfile.py

5.4.2. Profile Module

$ python -m profiling.tracing -m mypackage.mymodule

5.4.3. Sorting

  • -s: sort by column, default is time.

  • time: internal function execution time.

  • cumulative: execution time including called functions.

  • calls: number of function calls.

  • name: alphabetical function ordering.

$ python -m profiling.tracing -s cumulative script.py

5.4.4. Save Output

  • -o or --output: save output to file

$ python -m profiling.tracing -o myfile.prof myfile.py

You can inspect it using pstats:

import pstats

stats = pstats.Stats("myfile.prof")

stats.strip_dirs()
stats.sort_stats("cumulative")
stats.print_stats(30)

Inspect callers and callees:

stats.print_callers(20)
stats.print_callees(20)

stats.print_callers("my_function")
stats.print_callees("my_function")

5.4.5. Programmatic profiling

  • Use profiling.tracing to profile a function or code block programmatically.

from profiling.tracing import Profile

def myfunction():
    return sum(i * i for i in range(10_000_000))

with Profile() as profiler:
    myfunction()

profiler.print_stats()

This is convenient when you want to profile a specific execution region rather than the entire application.

You can also profile an individual function:

from profiling.tracing import Profile


def myfunction():
    return sum(i * i for i in range(10_000_000))

profiler = Profile()
result = profiler.runcall(myfunction)
profiler.print_stats()

5.4.6. Working With Profile Data Programmatically

You can access the collected statistics through pstats:

from profiling.tracing import Profile
import pstats


def myfunction():
    return sum(i * i for i in range(10_000_000))


profiler = Profile()

profiler.enable()
myfunction()
profiler.disable()

stats = pstats.Stats(profiler)
stats.sort_stats(pstats.SortKey.CUMULATIVE)
stats.print_stats(30)

This approach is useful for automated profiling workflows and regression analysis.