CKTIS / Python
cProfile.Profile
Een Profile-object verzamelt aanroepstatistieken en runcall geeft de normale uitkomst van de functie.
Versie: Python 3.14; repository image, production runtime not attested
Syntax
cProfile.Profile()
profiler.runcall(func, /, *args, **kwargs)Een Profile-object verzamelt aanroepstatistieken en runcall geeft de normale uitkomst van de functie.
create_stats() stopt de meting en legt de verzamelde statistieken vast. print_stats() drukt een tekstverslag af en dump_stats(path) slaat de gegevens op voor later gebruik met pstats.Stats. square(4) geeft 16 en het profiel telt één aanroep van square. Bij recursie onderscheidt pstats.Stats alle aanroepen van de primitieve aanroepen die buiten de recursie ontstaan. Met enable() en disable() of een with-blok begrens je de meting.
Tijden variëren met de belasting.
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() start het verzamelen van profielgebeurtenissen en disable() stopt dat. Een finally-blok stopt de meting ook na een uitzondering. Van drie aanroepen van work telt alleen de middelste mee.
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]
Voorbeelden
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"])
Resultaat
16 [1]
Tijden variëren met de belasting.