all Python 3cProfileterm
cProfile.Profile
running the profiler
The profiler class: switch it on with enable()/disable() or a with block to collect stats for just the code you care about.
Syntax
with cProfile.Profile() as pr: ...
A with block (3.8+) is safer than an enable()/disable() pair: the profile closes even on an exception. Only the current thread is profiled — work in a threading.Thread is invisible. ncalls like 177/1 for a recursive function means total calls / primitive calls. The profiler itself slows tiny calls, so absolute times are inflated: compare proportions and use timeit for precise timing.
Examples
import cProfile, pstats
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
with cProfile.Profile() as pr:
fib(10)
prof = pstats.Stats(pr).get_stats_profile()
print(prof.func_profiles['fib'].ncalls) # → 177/1
import cProfile
pr = cProfile.Profile()
pr.enable()
total = sum(range(100000))
pr.disable()
pr.print_stats(sort='tottime') # → ? таблица: время зависит от машины
See also
Open in the full glossarydocs.python.orgReport an inaccuracy