Python API¶
Profiler¶
The measurement engine. Tracks Python function calls and C extension calls using
sys.monitoring, measuring cumulative wall time per function.
Profiler also supports the context manager protocol as a convenience:
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.monitoringcallbacks on start, deregisters them on stop. get_result(name, sort="cumulative", limit=20) -> StatsResult- Build and return a
StatsResultfrom collected data.sortaccepts"cumulative","tottime", or"calls".limitcaps the number of rows. print_stats(name="block", sort="cumulative", limit=20)- Convenience method — calls
get_resultand 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:
Targeted context manager¶
Pass targets as a list of callables to restrict profiling to those functions:
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.