CKTIS / Python
cProfile.Profile
Profiles a callable while returning its ordinary result and retaining per-function statistics.
Version: Python 3.14; repository image, production runtime not attested
Syntax
cProfile.Profile()
profiler.runcall(func, /, *args, **kwargs)Profiles a callable while returning its ordinary result and retaining per-function statistics.
Call counts are stable for a fixed workload, while cumulative timing values depend on the machine and load.
runcall returns the function result, while pstats.Stats(profile) exposes primitive and total calls separately for recursion. Use enable() and disable(), or a with block, to limit collection to selected code. The example prints 16 and the single call count [1]. create_stats() stops collection and records the current statistics. print_stats() prints a text report, while dump_stats(path) writes data for later use with pstats.Stats.
import cProfile,pstats
def visit(n):
return visit(n-1)+1 if n else 1
p=cProfile.Profile()
assert p.runcall(visit,2)==3
stats=pstats.Stats(p).stats
counts=[v[:2] for k,v in stats.items() if k[2]=='visit']
assert counts==[(1,3)]
import contextlib,io,tempfile,os
p.enable()
visit(1)
p.create_stats()
visit(4)
assert [v[1] for k,v in p.stats.items() if k[2]=='visit']==[5]
with contextlib.redirect_stdout(io.StringIO()) as out: p.print_stats()
assert 'visit' in out.getvalue()
with tempfile.TemporaryDirectory() as d:
path=os.path.join(d,'prof')
p.dump_stats(path)
assert [v[1] for k,v in pstats.Stats(path).stats.items() if k[2]=='visit']==[5]
cProfile.Profile.enable · cProfile.Profile.disable
enable() starts collecting profiling events and disable() stops collection. A finally block stops measurement even after an exception. Of three work calls, only the middle call falls inside the measured interval.
import cProfile
def work(): return 5
p=cProfile.Profile()
work()
p.enable()
try: work()
finally: p.disable()
work()
counts=[r.callcount for r in p.getstats() if r.code is work.__code__]
assert counts==[1]
Examples
import cProfile
def square(n): return n * n
p = cProfile.Profile()
print(p.runcall(square, 4))
print([e.callcount for e in p.getstats() if getattr(e.code, "co_name", None) == "square"])
Result
16 [1]
runcall returns the function result, while pstats.Stats(profile) exposes primitive and total calls separately for recursion. Use enable() and disable(), or a with block, to limit collection to selected code. The example prints 16 and the single call count [1]. create_stats() stops collection and records the current statistics. print_stats() prints a text report, while dump_stats(path) writes data for later use with pstats.Stats.