Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

pstats.Stats.stats — raw profiling statistics

pstats.Stats.stats is a dictionary of profiling data keyed by filename, line number, and function name. Read call counts, internal time, cumulative time, and caller information directly instead of parsing a text report.

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

Syntax

stats = pstats.Stats(profiler)
cc, nc, tt, ct, callers = stats.stats[(filename, line_number, function_name)]

pstats.Stats.stats is an instance attribute, not a method. Each key is (filename, line_number, function_name), and each value is (cc, nc, tt, ct, callers). Even the complete key does not uniquely identify a function: two distinct lambda functions defined on the same source line have the same filename, line number, and function name (<lambda>), so they share a key.

cc counts primitive calls, excluding calls induced by recursion; nc counts all calls. tt is internal function time excluding subcalls, while ct is cumulative time including subcalls, in seconds. Do not sum every function's ct to obtain total program time: these intervals overlap.

callers maps caller function keys to profiler-dependent data. With cProfile, each value is (nc, cc, tt, ct) for that calling relationship — the count order is reversed compared with the outer tuple. With profile, each value is a call count. Recursion can make a function its own caller.

Treat this dictionary as a low-level CPython 3.14 implementation representation, not a portable format guarantee. Avoid manual mutation: the object also maintains totals and caches. strip_dirs() changes keys and can merge entries; sort_stats() establishes report order, not dictionary order. The example demonstrates deterministic counts rather than variable timings. This entry is based on repository code; the production runtime is not attested.

Examples

import cProfile
import pstats


def countdown(n):
    if n:
        countdown(n - 1)


profiler = cProfile.Profile()
profiler.runcall(countdown, 3)
stats = pstats.Stats(profiler)
key = (countdown.__code__.co_filename,
       countdown.__code__.co_firstlineno,
       countdown.__code__.co_name)
cc, nc, tt, ct, callers = stats.stats[key]
assert (cc, nc) == (1, 4)
assert key in callers
print(f"primitive={cc}, total={nc}")
print(f"recursive_caller={key in callers}")

Result

primitive=1, total=4
recursive_caller=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