Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

pstats.Stats — analyzing profiling results

pstats.Stats analyzes profiler data by sorting function statistics and producing reports. It does not measure execution itself; it accepts a saved profile or a profiler object.

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

Syntax

pstats.Stats(*filenames, stream=sys.stdout)
pstats.Stats(profile, stream=sys.stdout)

pstats.Stats accepts profile filenames or a cProfile.Profile or profile.Profile object. The stream parameter selects the report destination; its default is sys.stdout.

sort_stats(pstats.SortKey.CUMULATIVE) sorts descending by time including called functions. pstats.SortKey.TIME counts only time inside the function itself. print_stats(10) prints the first ten entries.

strip_dirs() permanently removes directory paths and may merge indistinguishable entries; sort afterward. Profile-file compatibility across Python versions, profilers, and operating systems is not guaranteed.

Examples

import cProfile
import io
import pstats


def work():
    return sum(range(10))


profiler = cProfile.Profile()
result = profiler.runcall(work)
report = io.StringIO()
stats = pstats.Stats(profiler, stream=report)
stats.sort_stats(pstats.SortKey.CUMULATIVE).print_stats()

print(result)
print("work" in report.getvalue())

Result

45
True

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources