CKTIS / Python
pstats — analyzing profiling results
The pstats module analyzes data from cProfile or profile: it sorts function statistics and produces reports that help locate expensive parts of a program.
Version: Python 3.14; repository image, production runtime not attested
Syntax
import pstats
stats = pstats.Stats(profile_or_filename)
stats.sort_stats(pstats.SortKey.CUMULATIVE).print_stats(10)pstats analyzes profiling results rather than measuring program execution itself. pstats.Stats accepts a profiler object or the name of a file containing its data.
pstats.Stats reads saved profiling data using marshal, which is not safe for untrusted or unauthenticated input. Do not load profiling files from untrusted sources or files whose authenticity has not been verified.
sort_stats(pstats.SortKey.TIME) orders by a function's own time, excluding called functions; pstats.SortKey.CUMULATIVE includes their time. print_stats(10) prints the first ten entries.
get_stats_profile() provides programmatic access. The example reads the call count for work, avoiding variable timing measurements.
Do not assume profiling-file compatibility across Python versions, profilers, or operating systems. strip_dirs() irreversibly removes paths from the object and can merge indistinguishable entries.
Examples
import cProfile
import pstats
def work():
return sum(range(10))
profiler = cProfile.Profile()
result = profiler.runcall(work)
stats = pstats.Stats(profiler)
functions = stats.get_stats_profile().func_profiles
print(result)
print(functions["work"].ncalls)Result
45 1
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.