Skip to content

Python API

Profiler

The measurement engine. Tracks Python function calls and C extension calls using sys.monitoring, measuring cumulative wall time per function.

from step3 import Profiler

p = Profiler()
p.start()
do_work()
p.stop()
p.print_stats()

Profiler also supports the context manager protocol as a convenience:

with Profiler() as p:
    do_work()
p.print_stats()

Targeted profiling

Pass a frozenset of keys to restrict tracking to specific functions. Outside of the Python API, the profit() factory handles key conversion for you — see below.

Methods

start() / stop()
Begin and end a profiling session. Registers sys.monitoring callbacks on start, deregisters them on stop.
get_result(name, sort="cumulative", limit=20) -> StatsResult
Build and return a StatsResult from collected data. sort accepts "cumulative", "tottime", or "calls". limit caps the number of rows.
print_stats(name="block", sort="cumulative", limit=20)
Convenience method — calls get_result and prints the formatted table to stdout.

profit

A singleton that acts as both a decorator and a context manager factory.

Context manager

profit() returns a Profiler instance ready to use as a context manager:

from step3 import profit

with profit() as p:
    do_work()

p.print_stats()

Targeted context manager

Pass targets as a list of callables to restrict profiling to those functions:

with profit(targets=[my_func]) as p:
    do_work()

p.print_stats()

Decorator

Applied directly to a function, profit wraps it so every call is profiled. Results accumulate on the profit singleton and can be printed after any number of calls:

from step3 import profit

@profit
def my_func(n):
    return sum(range(n))

for i in range(100):
    my_func(i)

profit.print_stats()

Attributes

sort: str
Default sort key for print_stats() in decorator mode. One of "cumulative", "tottime", "calls". Default: "cumulative".
limit: int
Maximum number of rows for print_stats() in decorator mode. Default: 20.