WissensdatenbankPrüfungszentrum
DEDeutsch
Sprache wählen13

CKTIS / Python

cProfile.Profile

Ein Profile-Objekt sammelt Aufrufstatistiken, während runcall das normale Funktionsergebnis liefert.

Version: Python 3.14; repository image, production runtime not attested

Syntax

cProfile.Profile()
profiler.runcall(func, /, *args, **kwargs)

Ein Profile-Objekt sammelt Aufrufstatistiken, während runcall das normale Funktionsergebnis liefert.

create_stats() beendet die Messung und hält die erfassten Statistiken fest. print_stats() gibt einen Textbericht aus, dump_stats(path) speichert die Daten zur späteren Auswertung mit pstats.Stats. square(4) ergibt 16, das Profil zählt einen Aufruf von square. Bei Rekursion unterscheidet pstats.Stats alle Aufrufe von den nicht durch Rekursion ausgelösten primitiven Aufrufen. enable() und disable() oder ein with-Block begrenzen den Messbereich.

Laufzeiten hängen von der Auslastung ab.

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() startet das Sammeln von Profilereignissen, disable() beendet es. Ein finally-Block beendet die Messung auch bei einer Ausnahme. Von drei work-Aufrufen liegt nur der mittlere im Messbereich.

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]

Beispiele

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"])

Ergebnis

16
[1]

Laufzeiten hängen von der Auslastung ab.

Quellen