Baza znanjaIzpitno središče
SLSlovenščina
Izberi jezik13

CKTIS / Python

cProfile.run

run profilira ukaze v imenskem prostoru glavnega modula.

Različica: Python 3.14; repository image, production runtime not attested

Sintaksa

cProfile.run(statement, filename=None, sort=-1)

run profilira ukaze v imenskem prostoru glavnega modula.

V CPythonu 3.14.9 run prestreže SystemExit iz ukaza in vrne None. ValueError se prenese na klicatelja. Pri podanem filename lahko pstats.Stats v obeh primerih prebere shranjene podatke. Njegov slovar je hkrati globalni in lokalni imenski prostor. Brez filename funkcija izpiše poročilo, urejeno po sort. S podano potjo shrani statistiko za pstats.Stats. Funkcija vrne None.

Primer iz začasne datoteke prebere en klic square.

import cProfile, pstats, tempfile, os, __main__
def probe(): return 5
__main__.__dict__['profile_probe']=probe
try:
    with tempfile.TemporaryDirectory() as directory:
        target=os.path.join(directory,'p.prof')
        assert cProfile.run("profile_probe()", target) is None
        assert [v[1] for k,v in pstats.Stats(target).stats.items() if k[2]=='probe']==[1]
finally: del __main__.__dict__['profile_probe']
with tempfile.TemporaryDirectory() as directory:
    for exc in ('SystemExit','ValueError'):
        path=os.path.join(directory,exc+'.prof')
        try: result=cProfile.run("raise "+exc+"()",path)
        except ValueError: assert exc=='ValueError'
        else: assert exc=='SystemExit' and result is None
        assert pstats.Stats(path).total_calls>0

Primeri

import cProfile
import pstats
from pathlib import Path
from tempfile import TemporaryDirectory

def square(n): return n * n

with TemporaryDirectory() as d:
    p = str(Path(d) / "sample.prof")
    cProfile.run("square(4)", p)
    print(sum(stat[1] for key, stat in pstats.Stats(p).stats.items() if key[2] == "square"))

Rezultat

1

Primer iz začasne datoteke prebere en klic square.

Viri