Baza wiedzyCentrum egzaminacyjne
PLPolski
Wybierz język13

CKTIS / Python

cProfile.run

run profiluje instrukcje w przestrzeni nazw modułu głównego.

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

Składnia

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

run profiluje instrukcje w przestrzeni nazw modułu głównego.

W CPython 3.14.9 run przechwytuje SystemExit profilowanej instrukcji i zwraca None. ValueError dociera do wywołującego. Przy podanym filename w obu przypadkach pstats.Stats odczytuje zapisane dane. Jego słownik pełni rolę zmiennych globalnych i lokalnych. Bez filename funkcja wyświetla raport uporządkowany według sort, a podana ścieżka kieruje statystyki do pliku dla pstats.Stats. Funkcja zwraca None.

Przykład odczytuje jedno wywołanie square z pliku tymczasowego.

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

Przykłady

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

Wynik

1

Przykład odczytuje jedno wywołanie square z pliku tymczasowego.

Źródła